<?php
/**
 * Created by PhpStorm.
 * User: sqq
 * Date: 2018/07/12
 * Time: 下午14:32
 */

class ApiServiceController extends BaseController {

    /**
     * @Author:      sqq
     * @DateTime:    2018-07-12 14:34:10
     * @Description: C端-首页-车辆状态接口
     * @link: http://www.activity.com/wechat/api3.0/CarStatus?token=668c155fab8dd6ef1e789b33ff6d040e
     */
    public function CarStatus(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }
            $begin_date = date("Y-m-d H:i:s",time());
            $end_date = date("Y-m-d H:i:s",time()-3*3600);

            $car_status = array(1,3);

            //查询取消或者终止的订单车辆
            //$cancel_car = Orders::where("user_id",$mkt_user->id)->whereIn("status",Orders::$car_cancel_status)->orderBy("created_at","desc","status","desc")->groupBy("car_no")->get();
            $re['car_status'] = '';
            //查询用户是否有正在服务中的车辆
            $service_car = UserCarInfo::service_car($users->id);
            header("Content-type:text/html;charset=utf-8");
            $arr = [];
            if(!is_null($service_car)){
                foreach($service_car as $_key1 => $_val1){
                    $arr[] = [
                        'car_no' => $_val1->car_no,
                        'order_id' => $_val1->order_id,
                        'order_time' => ''.$_val1->updated_at,
                        'next_mileage' => $this->next_maintain($_val1->user_car_id,$users->id, Orders::order_mileage($_val1->order_id)),
                        'next_time' => date("Y-m-d H:i:s",strtotime("+6 months", strtotime(''.$_val1->updated_at))),
                        'checkreport' => $this->is_checkreport($_val1->order_id),
                        'is_status' => 1,
                        'order_status' => $_val1->status,
                        'icon' => Config::get('config.car_brand_img_url').$_val1->icon,
                        'zhibo' => LiveAccessToken::LiveBroadcast($users->id,$_val1->order_id),
                    ];
                }
            }
            if(sizeof($arr) >= 3){
                $re['car_status'] = array_slice($arr, 0,3);
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $re);
                break;
            }

            //查询用户三个小时内的在店车辆
            $three_in_store =  UserCarInfo::three_in_store($users->id);
            if(!is_null($three_in_store)){
                //$result += $three_in_store->toArray();
                $result = array_column($arr,'car_no');
                foreach($three_in_store as $_key2 => $_val2){
                    if(!in_array($_val2->car_no, $result)){
                        //$result[] .= $_val2->car_no;
                        $arr[] = [
                            'car_no' => $_val2->car_no,
                            'order_id' => $_val2->order_id,
                            'order_time' => ''.$_val2->updated_at,
                            'next_mileage' => $this->next_maintain($_val2->user_car_id,$users->id, Orders::order_mileage($_val2->order_id)),
                            'next_time' => date("Y-m-d H:i:s",strtotime("+6 months", strtotime(''.$_val2->updated_at))),
                            'checkreport' => $this->is_checkreport($_val2->order_id),
                            'is_status' => 2,
                            'order_status' => $_val2->status,
                            'icon' => Config::get('config.car_brand_img_url').$_val2->icon,
                            'zhibo' => LiveAccessToken::LiveBroadcast($users->id,$_val2->order_id),
                        ];
                    }
                }
            }
            if(sizeof($arr) >= 3){
                $re['car_status'] = array_slice($arr, 0,3);
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $re);
                break;
            }

            //查询用户有没有默认车辆
            $default_car = UserCarInfo::detail_car($users->id);
            if(!is_null($default_car)){
                //$result += $default_car->toArray();
                $result = array_column($arr,'car_no');
                //foreach($default_car as $_val3){
                    if(!in_array($default_car->car_no, $result)){
                        $order = Orders::where('user_id',$default_car->user_id)->where("user_car_id",$default_car->id)->whereIn('status',[1112,1312,1412,1213,1214,1117,1217,1317,1417,1018])->where('order_type',1)->orderBy("created_at","desc")->first();
                        //$result[] .= $_val3->car_no;
                        if(!is_null($order)){
                            $arr[] = [
                                'car_no' => $order->car_no,
                                'order_id' => $order->order_id,
                                'order_time' => ''.$order->updated_at,
                                'next_mileage' => $this->next_maintain($order->user_car_id,$users->id,$order->mileage),
                                'next_time' => date("Y-m-d H:i:s",strtotime("+6 months", strtotime(''.$order->updated_at))),
                                'checkreport' => $this->is_checkreport($order->order_id),
                                'is_status' => 3,
                                'order_status' => $order->status,
                                'icon' => Config::get('config.car_brand_img_url').$default_car->icon,
                                'zhibo' => LiveAccessToken::LiveBroadcast($users->id,$order->order_id),
                            ];
                        }else{
                            $arr[] = [
                                'car_no' => $default_car->car_no,
                                'order_id' => $default_car->order_id,
                                'order_time' => ''.$default_car->updated_at,
                                'next_mileage' => $this->next_maintain($default_car->id,$users->id, Orders::order_mileage($default_car->order_id)),
                                //'next_time' => date("Y-m-d H:i:s",strtotime("+6 months", strtotime(''.$default_car->updated_at))),
                                'next_time' => '',
                                'checkreport' => $this->is_checkreport($default_car->order_id),
                                'is_status' => 3,
                                'order_status' => $default_car->status,
                                'icon' => Config::get('config.car_brand_img_url').$default_car->icon,
                                'zhibo' => LiveAccessToken::LiveBroadcast($users->id,$default_car->order_id),
                            ];
                        }
                    }
                //}
            }
            if(sizeof($arr) >= 3){
                $re['car_status'] = array_slice($arr, 0,3);
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $re);
                break;
            }

            //查询用户是否有在店车辆(大于三小时)
            $in_store = UserCarInfo::in_store($users->id);
            if(!is_null($in_store)){
                //$result += $in_store->toArray();
                $result = array_column($arr,'car_no');
                foreach($in_store as $_key4 => $_val4){
                    if(!in_array($_val4->car_no, $result)){
                        //$result[] .= $_val4->car_no;
                        $arr[] = [
                            'car_no' => $_val4->car_no,
                            'order_id' => $_val4->order_id,
                            'order_time' => ''.$_val4->updated_at,
                            'next_mileage' => $this->next_maintain($_val4->user_car_id,$users->id, Orders::order_mileage($_val4->order_id)),
                            'next_time' => date("Y-m-d H:i:s",strtotime("+6 months", strtotime(''.$_val4->updated_at))),
                            'checkreport' => $this->is_checkreport($_val4->order_id),
                            'is_status' => 4,
                            'order_status' => $_val4->status,
                            'icon' => Config::get('config.car_brand_img_url').$_val4->icon,
                            'zhibo' => LiveAccessToken::LiveBroadcast($users->id,$_val4->order_id),
                        ];
                    }
                }
            }
            if(sizeof($arr) >= 3){
                $re['car_status'] = array_slice($arr, 0,3);
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $re);
                break;
            }

            //查询用户所有车辆
            $user_car = UserCarInfo::user_car($users->id);
            if(!is_null($user_car)){
                //$result += $default_car->toArray();
                $result = array_column($arr,'car_no');
                foreach($user_car as $_key5 => $_val5 ){
                    if(!in_array($_val5->car_no, $result)){
                        $arr[] = [
                            'car_no' => $_val5->car_no,
                            'order_id' => $_val5->order_id,
                            'order_time' => ''.$_val5->updated_at,
                            'next_mileage' => $this->next_maintain($_val5->id,$users->id, Orders::order_mileage($_val5->order_id)),
                            //'next_time' => date("Y-m-d H:i:s",strtotime("+6 months", strtotime(''.$_val5->updated_at))),
                            'next_time' => '',
                            'checkreport' => $this->is_checkreport($_val5->order_id),
                            'is_status' => 5,
                            'order_status' => $_val5->status,
                            'icon' => Config::get('config.car_brand_img_url').$_val5->icon,
                            'zhibo' => LiveAccessToken::LiveBroadcast($users->id,$_val5->order_id),
                        ];
                    }
                }
            }
            if(sizeof($arr) > 0){
                $re['car_status'] = array_slice($arr, 0,3);
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $re);

        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "wechat/api3.0/CarStatus",  'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /*
     * 下次建议保养里程
     * 1.查找分类id为247  更换/拆装机油、机滤 找到包id
     * 2.floor((最新的订单里程-找到的服务单里程)/步长+1)*步长+找到的服务单里程  ((最新的订单/找到的服务单)/步长+1) 舍掉小数 取整
     * 3.步长 该车型 该耗材id 下的步长 supply_subject_car 表
     * */
    public function next_maintain($user_car_id,$user_id, $mileage){
        $product_package = ProductPackage::where('classify',247)->select('id')->get()->toArray();
        $pack_ids=array_column($product_package,'id');
        $temp = "";
        foreach($pack_ids as $key => $_i){
            if($key+1==count($pack_ids)){
                $temp.=$_i;
            }else{
                $temp.=$_i.',';
            }
        }
        $sql = 'SELECT
                      *
                    FROM
                      orders
                    WHERE user_car_id = '.$user_car_id.'
                      AND user_id = '.$user_id.'
                      AND STATUS IN (1117,1317,1018,1217,1417)
                      AND order_id IN
                      (SELECT DISTINCT
                        order_id
                      FROM
                        order_product
                      WHERE product_id IN ('.$temp.') AND STATUS = 1)
                    ORDER BY created_at DESC ;
                ';
        $res = DB::select($sql);
        if($res){
            $ssc = DataCarMaintenanceClassificationConfig::where('car_model_id',$res[0]->car_model_id)->where('supply_classification_id',2425)->where('status',1)->first();
            if(!is_null($ssc)){
                $next_mileage = floor(($mileage - $res[0]->mileage)/$ssc->step+1)*$ssc->step+$res[0]->mileage;
            }else{
                $next_mileage = floor(($mileage - $res[0]->mileage)/5000+1)*5000+$res[0]->mileage;
            }
        }else{
            $next_mileage = 0;
        }
        return $next_mileage;
    }


    public function is_checkreport($order_id){
        $order_detection = OrderDetection::where('order_id',$order_id)->first();
        $of = OrderFlows::where('order_id',$order_id)->select('status')->get()->toArray();
        $tmp1 = array();
        foreach($of as $_o){
            $tmp1[] = $_o['status'];
        }
        $status = array('status' => 2, 'report' => '', 'time' => '');//服务完成  检测中
        if(!is_null($order_detection) && !in_array('1419',$tmp1)){
            $status = array('status' => 3, 'report' => $order_detection, 'time' => $order_detection->updated_at);//有检测报告 显示分数  //检测完成
        }
        if(is_null($order_detection)){
            $status = array('status' => 1, 'report' => '', 'time' => '');  //没有检测报告  //没有检测报告
        }
        return $status;
    }


    /**
     * @Author:      sqq
     * @DateTime:   2018-09-05 10:26:29
     * @Description: 购物车角标
     * @Param: $token String 用户token
     * @link：http://www.activity.com/wechat/api3.0/shoppingSum?token=3c04221bedc65d21ecf07aaef3fd21b5
     */
    public function shopping_sum(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            //验证token
            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            $num = Shopping::where('user_id',$users->id)->where('status',1)->where('order_id', NULL)->count();

            $response = [
                'shopping_car' => [
                    'shopping_car_icon' =>  Config::get('config.service_list_shopping_car_icon'),
                    'num' => $num
                ],
                'APP_weizhan_service_url' => Config::get('config.APP_weizhan_service_url')
            ];
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $response);

        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "shopping_sum", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:          sqq
     * @DateTime:        2018-07-24 下午15:00
     * @Description:     api3.0 服务    [ C端服务列表 ]
     * @param string $token             用户token
     * @param int $model_id             车辆车型id
     * @link http://www.activity.com/wechat/api3.0/serviceList?city=%E5%8C%97%E4%BA%AC%E5%B8%82&token=2628d9f5d95ea4f138cbb9f68931a586&model=1
     */
    public function serviceList(){
        $validator = Validator::make(Input::all(),
            array(
//                'token' => 'required',
//                'brand' => 'required',
//                'series' => 'required',
//                'year' => 'required',
                'city' => 'required',
                //'model' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            if(Input::get("token")){
                $users = $this->verificationUserToken(Input::get("token"),$response);
                if(is_null($users)){
                    break;
                }
            }else{
                $users = (object)[];
                $users->id = 0;
            }



            //获取参数
            $brand = Input::get('brand');
            $series = Input::get('series');
            $year = urldecode(Input::get('year'));
            $model = Input::get('model');
            $city_name = Input::get('city');
            header("Content-type:text/html;charset=utf-8");
            //判断城市是否开放
            $city_id = PublicApi::Judge_city($city_name);
            if($city_id == 0){
                //城市未开放
                $response = Lang::get("error.service_list_city_empty_error_30011");
                break;
            }

            //判断当前城市是否有门店开放
            $shop_id = MaintenanceShops::where('status',1)->where('city_id',$city_id)->where('is_show',1)->first();
            if(empty($shop_id)){
                //城市没有适配门店
                $response = Lang::get("error.service_list_city_shop_empty_error_30012");
                break;
            }

            //如果用户登录，查询用户车辆信息（服务单3小时内>默认车辆）
            if(!is_null($users)){
                $car_status = array(1,3);
                $service_car = Orders::join("anhui_data.car_brand","orders.car_brand_id","=","anhui_data.car_brand.id")->join("user_car_info","orders.user_car_id","=","user_car_info.id")->join("anhui_data.car_standard_info","user_car_info.car_model_id","=","anhui_data.car_standard_info.id")->where("orders.user_id",$users->id)->whereIn("orders.status",Orders::$car_service_status)->where("order_type",1)->whereIn("user_car_info.status",$car_status)->orderBy("orders.updated_at","desc")->select("orders.user_id","orders.car_no","anhui_data.car_brand.name","anhui_data.car_brand.icon","orders.user_car_id","user_car_info.car_model_id")->first();
                //默认车辆
                if(empty($service_car)){
                    $service_car = UserCarInfo::join("anhui_data.car_brand","user_car_info.car_brand_id","=","anhui_data.car_brand.id")->join("anhui_data.car_standard_info","user_car_info.car_model_id","=","anhui_data.car_standard_info.id")->where("is_default",1)->where("user_id",$users->id)->whereIn("user_car_info.status",$car_status)->select("user_car_info.user_id","user_car_info.car_no","user_car_info.id","anhui_data.car_brand.icon","anhui_data.car_brand.name","anhui_data.car_standard_info.model_name","user_car_info.car_model_id")->first();
                }
                if(!empty($service_car)){
                    $service_car->message = UserCarInfo::getCarStandardInfo($service_car->car_model_id);
                    $service_car->icon = Config::get('config.car_brand_img_url').$service_car->icon;
                }
            }else{
                $service_car = '';
            }
            if(!empty($model)){
                //查询分类
                $product_class = ProductClassification::get()->toArray();
                if(!empty($product_class)){
                    //获取每个分类下面ahp配置的服务
                    foreach($product_class as $_key => $_val){
                        $product_class[$_key]['ahp_service'] = AhpService::where('classify',$_val['id'])->where('status',1)->select('id','service_name','classify','service_type','thumbnail')->get()->toArray();
                    }

                    //查询推荐中的ahp服务
                    $recommend = AhpService::where('status',1)->where('is_recommend',1)->select('id','service_name','classify','service_type','thumbnail')->get()->toArray();
                    $service_list_recommend = Config::get('config.service_list_recommend_icon');
                    if(!empty($recommend)){
                        $service_list_recommend['ahp_service'] = $recommend;
                        //array_unshift($service_list_recommend['ahp_service'],$recommend);
                    }
                    array_unshift($product_class,$service_list_recommend);
                    //判断获取的产品包/活动包是否适配了当前城市，没有适配就从数组中删除
                    foreach($product_class as $key => $val){
                        //$product_class[$key]['icon_url'] = Config::get('config.service_list_icon_url');
                        $product_class[$key]['icon'] = Config::get('config.service_list_icon_url').$val['icon'];
                        $product_class[$key]['click_icon'] = Config::get('config.service_list_icon_url').$val['click_icon'];
                        //$product_class[$key]['thumb'] = Config::get('config.ahp_upload_files_url');
                        if($val['ahp_service']){
                            foreach($val['ahp_service'] as $k => $v) {
                                if ($v['service_type'] == 1) {
                                    $product_class[$key]['ahp_service'][$k]['service'] = AhpServiceMktCms::join('product_activity','ahp_service_mkt_cms.mkt_cms_id','=','product_activity.id')->where('ahp_service_mkt_cms.service_id',$v['id'])->select('product_activity.id','product_activity.name','price','product_activity.type','discount')->get();
                                    //mkt活动包
                                    //获取服务所适配的活动包/产品包
//                                    $res = AhpServiceMktCms::leftjoin('product_activity_city', 'ahp_service_mkt_cms.mkt_cms_id', '=', 'product_activity_city.product_activity_id')
//                                        ->leftjoin('product_activity_package', 'product_activity_city.product_activity_id', '=', 'product_activity_package.package_id')
//                                        ->leftjoin('product_activity_package_item', 'product_activity_package.package_id', '=', 'product_activity_package_item.product_activity_package_id')
//                                        //->leftjoin('anhui_data.supply_product_item','product_activity_package_item.supply_item_id','=','anhui_data.supply_product_item.supply_item_id')
//                                        ->where('ahp_service_mkt_cms.service_id', $v['id'])
//                                        ->where('product_activity_city.status', 1)
//                                        ->where('product_activity_city.city_id', $city_id)
//                                        //->where('anhui_data.supply_product_item.status',1)
//                                        // ->where('anhui_data.supply_product_item.car_model_id',$model)
//                                        ->count();
                                } else {
                                    //cms产品包
                                    $product_class[$key]['ahp_service'][$k]['service'] = AhpServiceMktCms::join('product_package','ahp_service_mkt_cms.mkt_cms_id','=','product_package.id')->where('ahp_service_mkt_cms.service_id',$v['id'])->select('product_package.id','product_package.name')->get();
//                                    $res = AhpServiceMktCms::leftjoin('product_pack_city', 'ahp_service_mkt_cms.mkt_cms_id', '=', 'product_pack_city.pack_id')
//                                        ->leftjoin('product_pack_item', 'ahp_service_mkt_cms.mkt_cms_id', '=', 'product_pack_item.pack_id')
//                                        //->leftjoin('anhui_data.supply_product_item','product_pack_item.item_id','=','anhui_data.supply_product_item.supply_item_id')
//                                        ->leftjoin("supply_classification", "supply_classification.id", "=", "product_pack_item.item_id")
//                                        ->where('ahp_service_mkt_cms.service_id', $v['id'])
//                                        ->where('product_pack_city.status', 1)
//                                        ->where('product_pack_item.type', 3)
//                                        ->where('product_pack_item.status', 1)
//                                        //->where('anhui_data.supply_product_item.status',1)
//                                        //->where('anhui_data.supply_product_item.car_model_id',$model)
//                                        ->select("supply_classification.name", "product_pack_item.item_id")
//                                        ->count();
                                }
//                                if ($res == 0) {
//                                    //array_splice($product_class[$key]['ahp_service'], $k, 1);break;
//                                    if(isset($product_class[$key]['ahp_service'][$k])){
//                                        unset($product_class[$key]['ahp_service'][$k]);break;
//                                    }
//                                    continue;
//                                }

                                $a = $product_class[$key]['ahp_service'][$k]['service'];
                                $ahp_auth_item_id = AhpServiceClassification::getItem($v['id']);
                                if(!is_null($a)){
                                    foreach($a as $s_key => $s_val){
                                        //查询服务包适配的所有服务
                                        $product_pack_item = '';
                                        //$mkt_cms = array_column($product_class[$key]['ahp_service'][$k]['service']->toArray(), 'id');
                                        $mkt_cms = array($s_val->id);
                                            if ($mkt_cms) {
                                                if ($v['service_type'] == 1) { //mkt
                                                    $pap = ProductActivityPackage::leftJoin("product_package", "product_activity_package.package_id", "=", "product_package.id")
                                                        ->whereIn('product_activity_id', $mkt_cms)
                                                        ->distinct('package_id')
                                                        ->groupBy('package_id')
                                                        ->select('package_id', 'product_activity_package.id', 'product_package.name')->get();
                                                    if (!empty($pap)) {
                                                        $pap = $pap->toArray();
                                                        $package_id = array_column($pap, 'package_id');
                                                        //foreach ($pap as $value){
                                                        $product_pack_item = ProductPackItem::leftjoin("supply_classification", "supply_classification.id", "=", "product_pack_item.item_id")
                                                            //->where("pack_id",$value['package_id'])
                                                            ->whereIn("pack_id", $package_id)
                                                            ->where("type", 3)
                                                            ->where("product_pack_item.status", 1)
                                                            ->distinct('product_pack_item.item_id')
                                                            ->select("supply_classification.name", "product_pack_item.item_id")
                                                            ->get()->toArray();
                                                        // }
                                                        //$value->id => product_activity_package_id
                                                    } else {
                                                        $product_pack_item = '';
                                                    }
                                                } else {
                                                    //cms
                                                    $product_pack_item = ProductPackItem::leftjoin("supply_classification", "supply_classification.id", "=", "product_pack_item.item_id")
                                                        ->whereIn("pack_id", $mkt_cms)
                                                        ->where("type", 3)
                                                        ->where("product_pack_item.status", 1)
                                                        ->distinct('product_pack_item.item_id')
                                                        ->select("supply_classification.name", "product_pack_item.item_id")
                                                        ->groupBy("product_pack_item.item_id")
                                                        ->get()->toArray();

                                                }
                                            } else {
                                                $product_pack_item = '';
                                            }
                                            //判断服务中的耗材是否有推荐，没有就删除
//判断是基础包还是活动包
                                            $product_class[$key]['ahp_service'][$k]['service'][$s_key]['product_pack_item'] = $product_pack_item;
                                            $arr = [];
                                            $item_id = [];
                                            if ($product_class[$key]['ahp_service'][$k]['service'][$s_key]['product_pack_item']) {
                                                foreach ($product_class[$key]['ahp_service'][$k]['service'][$s_key]['product_pack_item'] as $_id) {
                                                    if (!is_null($ahp_auth_item_id)){
                                                        foreach ($ahp_auth_item_id as $_itme_id) {
                                                            if (((int)$_itme_id->item_id == (int)$_id['item_id'])) {
                                                                //echo $_itme_id->item_id .' | ';
                                                                $arr = DataSupplyProductItem::getDefaultC($model, $_id['item_id']);
                                                                if (is_null($arr)) {
                                                                    if (isset($product_class[$key]['ahp_service'][$k]['service'][$s_key])) {
                                                                        unset($product_class[$key]['ahp_service'][$k]['service'][$s_key]);
                                                                        continue;
                                                                    }
                                                                    //array_splice($product_class[$key]['ahp_service'], $k, 1);continue;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                    }
                                }

                            }
                        }else{
                            unset($product_class[$key]);
                        }
                    }
                }
               //die;
                $tmps = [];
                if($product_class){
//                    foreach($product_class as $product_key => &$product_val){
//                        $service_val['ahp_service'] = json_decode(json_encode($product_val['ahp_service']),true);
//                        if(!empty($product_val['ahp_service'])){
//                            foreach($product_val['ahp_service'] as $service_key => &$service_val){
//                                $service_val['service'] = json_decode(json_encode($service_val['service']),true);
//                                if(!empty($service_val['service'])){
//                                    $product_class[$product_key]['ahp_service'][$service_key]['thumbnail'] = Config::get('config.ahp_upload_files_url').$service_val['thumbnail'];
//                                }else{
//                                    unset($product_class[$product_key]['ahp_service'][$service_key]);continue;
//                                }
//                            }
//                        }else{
//                            unset($product_class[$product_key]);continue;
//                        }
//                    }
                    foreach($product_class as &$product_val){
                        if(!empty($product_val['ahp_service'])){
                           $q = [];
                           $r = [];
                            foreach($product_val['ahp_service'] as &$service_val){
                                $service_val['service'] = json_decode(json_encode($service_val['service']),true);
                                if(!empty($service_val['service'])){
                                    $service_val['thumbnail'] = Config::get('config.ahp_upload_files_url').$service_val['thumbnail'];

                                    array_push($q,$service_val);
                                    $r = array(
                                        'id' => $product_val['id'],
                                        'name' => $product_val['name'],
                                        'icon' => $product_val['icon'],
                                        'click_icon' => $product_val['click_icon'],
                                        'ahp_service' => $q,
                                    );
                                    //array_push($r['ahp_service'],$service_val);
                                }
                            }
                            if($r){
                                array_push($tmps,$r);
                            }
                        }
                    }
                }
            }else{
                $service_car = [];
                $product_class = [];
                $tmps = [];
            }
            array_push($tmps,Config::get('config.service_list_qita_icon'));
            array_multisort($tmps);
            if(!is_null($users)){
                $num = Shopping::where('user_id',$users->id)->where('status',1)->where('order_id', NULL)->count();
            }else{
                $num = 0;
            }
            //die;
            $response = [
                'is_login' => is_null($users) ? 1 : 2,  //1-未登录 2-已登录
                'car_message' => $service_car,
                'serviceList' => $tmps,
                'shopping_car' => [
                    'shopping_car_icon' =>  Config::get('config.service_list_shopping_car_icon'),
                    'num' => $num
                ],
                'APP_weizhan_service_url' => Config::get('config.APP_weizhan_service_url')
            ];


            $response = array('code' => 0, 'msg' => 'ok', 'result' => $response);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "wechat/api3.0/serviceList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:          sqq
     * @DateTime:        2018-07-24 下午17:10
     * @Description:     api3.0 服务    [ C端服务详情 基础信息接口  配合serviceShowPrice接口使用]
     * @param string $token             用户token
     * @param int $id                 服务包id
     * @param int $city                 城市名称
     * @link
     */
    public function serviceShow(){
        $validator = Validator::make(Input::all(),
            array(
                //'token' => 'required',
                'id' => 'required',
                'city' => 'required',
                'car_model_id' => 'required',
                //'car_model_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //获取参数
            $id = Input::get('id');
            $city_name = Input::get('city');
            $car_model_id = Input::get('car_model_id');
            //判断城市是否开放
            $city_id = PublicApi::Judge_city($city_name);
            if($city_id == 0){
                //城市未开放
                $response = Lang::get("error.service_list_city_empty_error_30011");
                break;
            }

            //查询服务包基本信息
            $service = AhpService::with('desc')->where('id',$id)->where('status',1)->select('id','service_name','first_picture','service_type')->first();

            if(is_null($service)){
                $response = Lang::get("error.service_show_empty_error_30013");
                break;
            }

            $service->url =  Config::get('config.ahp_upload_files_url');

            if($service->service_type == 1){
                $service->service = AhpServiceMktCms::join('product_activity','ahp_service_mkt_cms.mkt_cms_id','=','product_activity.id')->where('ahp_service_mkt_cms.service_id',$id)->select('product_activity.id','product_activity.name','price','product_activity.type','discount')->get();
            }else{
                $service->service = AhpServiceMktCms::join('product_package','ahp_service_mkt_cms.mkt_cms_id','=','product_package.id')->where('ahp_service_mkt_cms.service_id',$id)->select('product_package.id','product_package.name')->get();
            }

            $ahp_auth_item_id = AhpServiceClassification::getItem($id);
            if(!is_null($service->service)){
                foreach($service->service as $key => $val){
                    if ($service->service_type == 1) { //mkt
                        $pap = ProductActivityPackage::leftJoin("product_package", "product_activity_package.package_id", "=", "product_package.id")
                            ->where('product_activity_id', $val->id)
                            ->distinct('package_id')
                            ->groupBy('package_id')
                            ->select('package_id', 'product_activity_package.id', 'product_package.name')->get();
                        if (!empty($pap)) {
                            $pap = $pap->toArray();
                            $package_id = array_column($pap, 'package_id');
                            $product_pack_item = ProductPackItem::leftjoin("supply_classification", "supply_classification.id", "=", "product_pack_item.item_id")
                                //->where("pack_id",$value['package_id'])
                                ->where("product_pack_item.pack_id", $package_id)
                                ->where("product_pack_item.type", 3)
                                ->where("product_pack_item.status", 1)
                                ->distinct('product_pack_item.item_id')
                                ->select("supply_classification.name", "product_pack_item.item_id")
                                ->get()->toArray();
                        } else {
                            $product_pack_item = '';
                        }
                    } else {
                        //cms
                        $product_pack_item = ProductPackItem::leftjoin("supply_classification", "supply_classification.id", "=", "product_pack_item.item_id")
                            ->where("product_pack_item.pack_id", $val->id)
                            ->where("product_pack_item.type", 3)
                            ->where("product_pack_item.status", 1)
                            ->distinct('product_pack_item.item_id')
                            ->select("supply_classification.name", "product_pack_item.item_id")
                            ->groupBy("product_pack_item.item_id")
                            ->get()->toArray();
                    }
                    //判断服务中的耗材是否有推荐，没有就删除
                    $service->service[$key]->pack_item = $product_pack_item;
                    $arr = [];
                    $item_id = [];
                    if ($service->service[$key]->pack_item) {
                        foreach ($service->service[$key]->pack_item as $_id) {
                            if (!is_null($ahp_auth_item_id)){
                                foreach ($ahp_auth_item_id as $_itme_id) {
                                    if (((int)$_itme_id->item_id == (int)$_id['item_id'])) {
                                        $arr = DataSupplyProductItem::getDefaultC($car_model_id, $_id['item_id']);
                                        if (is_null($arr)) {
                                            if (isset($service->service[$key])) {
                                                unset($service->service[$key]);
                                                continue;
                                            }
                                            //array_splice($product_class[$key]['ahp_service'], $k, 1);continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(Input::get("token")){
                $users=$this->verificationUserToken(Input::get("token"),$response);
                if(is_null($users)){
                    break;
                }
            }
            if(!is_null($service->service)){
                foreach($service->service as $_key => $_val){
                    $desc_id = AhpServiceMktCms::where('service_id',$id)->where('mkt_cms_id',$_val->id)->first();
                    $detail = AhpServiceMktCms::join('ahp_service_mkt_cms_desc','ahp_service_mkt_cms.id','=','ahp_service_mkt_cms_desc.service_mkt_cms_id')->where('ahp_service_mkt_cms_desc.service_mkt_cms_id',$desc_id->id)->select('ahp_service_mkt_cms_desc.desc')->get();
                    if(!is_null($detail)){
                        $service->service[$_key]->detail = array_column($detail->toArray(),'desc');
                    }
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $service);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "serviceShow", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-28 11:17:52
     * @Description: 服务详情  价格计算
     * @link http://www.activity.com/wechat/api3.0/serviceShowPrice?id=1&service_type=1&city=%E5%8C%97%E4%BA%AC%E5%B8%82&car_model_id=1&token=86ba207fc05f4586cfd87fb33231a5e0
     */
    public function serviceShowPrice(){
        $validator = Validator::make(Input::all(),
            array(
                'id' => 'required',
                'service_type' => 'required',
                'city' => 'required',
                'car_model_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //获取参数
            $city_name = Input::get('city');
            $service_type = Input::get('service_type');
            $id = Input::get('id');
            $car_model_id = Input::get('car_model_id');

            //判断城市是否开放
            $city_id = PublicApi::Judge_city($city_name);
            if($city_id == 0){
                //城市未开放
                $response = Lang::get("error.service_list_city_empty_error_30011");
                break;
            }

            //判断当前城市是否有门店开放
            $shop_id = MaintenanceShops::where('status',1)->where('city_id',$city_id)->where('is_show',1)->first();
            if(empty($shop_id)){
                //城市没有适配门店
                $response = Lang::get("error.service_list_city_shop_empty_error_30012");
                break;
            }

            if(Input::get("token")){
                $users = $this->verificationUserToken(Input::get("token"),$response);
                if(is_null($users)){
                    break;
                }
            }else{
                $users = (object)[];
                $users->id = 0;
            }


            //判断是基础包还是活动包
            if($service_type == 1){
                $package_arr = $this->MktPrice($car_model_id,$city_id,$id,$users);
            }else{
                $package_arr = $this->CmsPrice($car_model_id,$city_id,$id,$users);
            }

            if(!empty($package_arr) && array_key_exists('code',$package_arr)){
                return json_encode($package_arr);break;
            }
            if(empty($package_arr)){
                return json_encode(array('code' => 10233, 'msg' => '计算价格失败'));
            }

            if(Input::get("token")){
                $users = $this->verificationUserToken(Input::get("token"),$response);
                if(is_null($users)){
                    break;
                }
                if($service_type == 2){
                    $now_member=MemberOrdinary::find($users->member);
                    $now_data=UserMember::where("user_id",$users->id)->where("member",$users->member)->orderBy("created_at","desc")->first();
                    $pt_member['dis']=isset($now_member->dis) ? $now_member->dis:1;
                    $pt_member['created_at']=isset($now_data->created_at) ? $now_data->created_at :'';
                    $pt_member['relation']='无';
                    $pt_member['type']=3;

                    $mtu_member=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                        ->where("member_temporary_user.user_id",$users->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->orderBy("member_temporary.dis","asc")->select("member_temporary.dis","member_temporary_user.created_at")->first();

                    $ls_member['dis']=isset($mtu_member->dis) ? $mtu_member->dis:1;
                    $ls_member['created_at']=isset($mtu_member->created_at) ? $mtu_member->created_at :'';
                    $ls_member['relation']='无';
                    $ls_member['type']=4;

                    if($pt_member['dis']<=$ls_member['dis']){
                        $arr[]=$pt_member;
                    }else{
                        $arr[]=$ls_member;
                    }
                    foreach($arr as $key=>$_arr){
                        $dis[$key]=$_arr['dis'];
                        $created_at[$key]=$_arr['created_at'];
                    }
                    array_multisort($dis, SORT_ASC, $created_at, SORT_DESC, $arr);
                    $dis_arr=$arr[0];
                    $dis_last['dis']=$dis_arr['dis'];
                    $dis_last['relation']=$dis_arr['relation'];
                    $dis_last['type']=$dis_arr['type'];
                    $package_arr['count_amount'] = $package_arr['count_amount'] * $dis_last['dis'];
                    $package_arr['discount_rate'] = $dis_last['dis'];
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $package_arr);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "serviceShowPrice", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      sqq
     * @DateTime:    2018-07-28 08:51:52
     * @Description: 服务列表页面加载 [返回车辆信息] [前端传值原样返回，前端未传值返回数据库信息]
     * @link http://www.activity.com/wechat/api3.0/service_onload?city=%E5%8C%97%E4%BA%AC%E5%B8%82&token=86ba207fc05f4586cfd87fb33231a5e0
     */
    public function service_onload(){
        $validator = Validator::make(Input::all(),
            array(
                //'city' => 'required',
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //获取参数
            $city_name = Input::get('city');

            //判断城市是否开放
//            $city_id = PublicApi::Judge_city($city_name);
//            if($city_id == 0){
//                //城市未开放
//                $response = Lang::get("error.service_list_city_empty_error_30011");
//                break;
//            }

            //判断当前城市是否有门店开放
//            $shop_id = MaintenanceShops::where('status',1)->where('city_id',$city_id)->where('is_show',1)->first();
//            if(empty($shop_id)){
//                //城市没有适配门店
//                $response = Lang::get("error.service_list_city_shop_empty_error_30012");
//                break;
//            }

            $service_car = '';
            if(Input::get("token")){
                $users = $this->verificationUserToken(Input::get("token"),$response);
                if(is_null($users)){
                    break;
                }else{
                    //如果用户登录，查询用户车辆信息（服务单3小时内>默认车辆）
                    $car_status = array(1,3);
                    $service_car = Orders::join("anhui_data.car_brand","orders.car_brand_id","=","anhui_data.car_brand.id")->join("user_car_info","orders.user_car_id","=","user_car_info.id")->join("anhui_data.car_standard_info","user_car_info.car_model_id","=","anhui_data.car_standard_info.id")->where("orders.user_id",$users->id)->whereIn("orders.status",Orders::$car_service_status)->where("order_type",1)->whereIn("user_car_info.status",$car_status)->orderBy("orders.updated_at","desc")->select("anhui_data.car_brand.icon","anhui_data.car_brand.id as car_brand_id","anhui_data.car_brand.name",'anhui_data.car_standard_info.series_name_id as car_series_id','anhui_data.car_standard_info.series_name','anhui_data.car_standard_info.model_year',"anhui_data.car_standard_info.id as car_model_id","anhui_data.car_standard_info.model_name","orders.car_no","orders.user_car_id","user_car_info.is_default")->first();
                    //默认车辆
                    if(empty($service_car)){
                        $service_car = UserCarInfo::join("anhui_data.car_brand","user_car_info.car_brand_id","=","anhui_data.car_brand.id")->join("anhui_data.car_standard_info","user_car_info.car_model_id","=","anhui_data.car_standard_info.id")->where("is_default",1)->where("user_id",$users->id)->whereIn("user_car_info.status",$car_status)->select("anhui_data.car_brand.icon","anhui_data.car_brand.id as car_brand_id","anhui_data.car_brand.name",'anhui_data.car_standard_info.series_name_id as car_series_id','anhui_data.car_standard_info.series_name','anhui_data.car_standard_info.model_year',"anhui_data.car_standard_info.id as car_model_id","anhui_data.car_standard_info.model_name","user_car_info.car_no","user_car_info.id as user_car_id","user_car_info.is_default")->first();
                    }
                    if(empty($service_car)){
                        $service_car = UserCarInfo::join("anhui_data.car_brand","user_car_info.car_brand_id","=","anhui_data.car_brand.id")->join("anhui_data.car_standard_info","user_car_info.car_model_id","=","anhui_data.car_standard_info.id")->where("user_id",$users->id)->whereIn("user_car_info.status",$car_status)->select("anhui_data.car_brand.icon","anhui_data.car_brand.id as car_brand_id","anhui_data.car_brand.name",'anhui_data.car_standard_info.series_name_id as car_series_id','anhui_data.car_standard_info.series_name','anhui_data.car_standard_info.model_year',"anhui_data.car_standard_info.id as car_model_id","anhui_data.car_standard_info.model_name","user_car_info.car_no","user_car_info.id as user_car_id","user_car_info.is_default")->orderBy('user_car_info.id','asc')->first();
                        if(empty($service_car)){
                            $response = Lang::get("error.user_car_not_exit_error_1019");
                            break;
                        }
                    }
                }
                if(!is_null($service_car)){
                    //$service_car->icon = Config::get('config.car_brand_img_url').$service_car->icon;
                    $service_car->car_brand_img_url = Config::get('config.car_brand_img_url');
                    $service_car->car_id = $service_car->user_car_id;
                }

            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $service_car);
        }while(false);
         Log::info("info", array("system" => "api3.0" ,"event" => "service_onload", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-28 13:17:52
     * @Description: 服务列表 --添加购物车
     * @link http://www.activity.com/wechat/api3.0/addShoppingCart?token=86ba207fc05f4586cfd87fb33231a5e0&service_id=1&mkt_cms_id=142&service_type=1&car_id=2&car_model_id=1&city=%E5%8C%97%E4%BA%AC%E5%B8%82
     */
    public function addShoppingCart(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'service_id' => 'required',
                'mkt_cms_id' => 'required',
                'service_type' => 'required',
                'car_id' => 'required',
                'car_model_id' => 'required',
                'city' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //获取参数
            $car_id = Input::get('car_id');
            $service_id = Input::get('service_id');
            $mkt_cms_id = Input::get('mkt_cms_id');
            $service_type = Input::get('service_type');
            $car_model_id = Input::get('car_model_id');
            $city_name = Input::get('city');

            //判断城市是否开放
            $city_id = PublicApi::Judge_city($city_name);
            if($city_id == 0){
                //城市未开放
                $response = Lang::get("error.service_list_city_empty_error_30011");
                break;
            }

            //根据用户车辆临时表查询用户车辆信息
            $car = UserCarInfoInquiry::where('id',$car_id)->where('user_id',$users->id)->where('status',1)->first();
            if(is_null($car)){
                $response = Lang::get("error.user_car_not_exit_error_1019");
                break;
            }

            //查询购物车是否有当前用户的商品
            $shopping = Shopping::where('user_id',$users->id)->where('status',1)->where('type',2)->get();

            if(!is_null($shopping)){

                //判断车型信息是否相符
                $model_id = array_column($shopping->toArray(),'car_model_id');
                if(!empty($model_id)){
                    $model_id = $model_id[0];
                    if($car_model_id != $model_id){
                        $response = Lang::get("error.user_car_not_equally_error_1020");
                        break;
                    }
                }

                $data = [];
                foreach($shopping as $key => $val){
                    $data[] = [
                        'id' => $val->mkt_cms_id,
                        'service_type' => $val->service_type,
                    ];
                }
                $data = json_encode($data);
                $result = AhpService::city_shop($data, $users);
                $data1 = array(array('id' => $mkt_cms_id, 'service_type' => $service_type));
                $data1 = json_encode($data1);
                $result1 = AhpService::city_shop($data1, $users);
                if($result['id'] && $result1['id']){
                    $raw = array_intersect($result['id'], $result1['id']);
                    if(empty($raw)){
                        $response = Lang::get("error.service_shopping_car_error_1030");
                        break;
                    }
                }

//                if($service_type == 1){
//                    //查询购物车中所有商品的适配门店
//                    $shopping_mkt_cms_id = array_column($shopping->toArray(),'mkt_cms_id');
//                    $shopping_cart_shop = ProductActivityCity::whereIn('product_activity_id',$shopping_mkt_cms_id)->distinct()->where('status',1)->select('city_id')->get();
//
//                    $service_shop = ProductActivityCity::where('product_activity_id',$mkt_cms_id)->distinct()->where('status',1)->select('city_id')->get();
//
//                    if(!is_null($shopping_cart_shop) && !is_null($service_shop)){
//                        $shopping_cart_shop = array_column($shopping_cart_shop->toArray(),'city_id');
//                        $service_shop = array_column($service_shop->toArray(),'city_id');
//                        if($intersection = array_intersect($shopping_cart_shop, $service_shop)){
//                            if(empty($intersection)){
//                                $response = Lang::get("error.user_car_not_equally_error_1020");
//                                break;
//                            }
//                        }
//                    }
//                }

                //判断是否重复提交
//                $is_choose = Shopping::where('user_car_info_inquiry_id',$car_id)->where('user_id',$users->id)->where('status',1)->where('service_type',$service_type)->where('service_id',$service_id)->where('mkt_cms_id',$mkt_cms_id)->where('type',2)->first();
//                if(!is_null($is_choose)){
//                    $response = Lang::get("error.user_car_choose_error_1022");
//                    break;
//                }
            }

            //判断是基础包还是活动包
            if($service_type == 1){
                $package_arr = $this->MktPrice($car_model_id,$city_id,$mkt_cms_id,$users);
            }else{
                $package_arr = $this->CmsPrice($car_model_id,$city_id,$mkt_cms_id,$users);
            }
            if(!empty($package_arr) && array_key_exists('code',$package_arr)){
                return json_encode($package_arr);
            }

            if($service_type == 2){
                $now_member=MemberOrdinary::find($users->member);
                $now_data=UserMember::where("user_id",$users->id)->where("member",$users->member)->orderBy("created_at","desc")->first();
                $pt_member['dis']=isset($now_member->dis) ? $now_member->dis:1;
                $pt_member['created_at']=isset($now_data->created_at) ? $now_data->created_at :'';
                $pt_member['relation']='无';
                $pt_member['type']=3;
                $mtu_member=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                    ->where("member_temporary_user.user_id",$users->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->orderBy("member_temporary.dis","asc")->select("member_temporary.dis","member_temporary_user.created_at")->first();

                $ls_member['dis']=isset($mtu_member->dis) ? $mtu_member->dis:1;
                $ls_member['created_at']=isset($mtu_member->created_at) ? $mtu_member->created_at :'';
                $ls_member['relation']='无';
                $ls_member['type']=4;

                if($pt_member['dis']<=$ls_member['dis']){
                    $arr[]=$pt_member;
                }else{
                    $arr[]=$ls_member;
                }
                foreach($arr as $key=>$_arr){
                    $dis[$key]=$_arr['dis'];
                    $created_at[$key]=$_arr['created_at'];
                }
                array_multisort($dis, SORT_ASC, $created_at, SORT_DESC, $arr);
                $dis_arr=$arr[0];
                $dis_last['dis']=$dis_arr['dis'];
                $dis_last['relation']=$dis_arr['relation'];
                $dis_last['type']=$dis_arr['type'];

                $package_arr['count_amount'] = $package_arr['count_amount'] * $dis_last['dis'];
            }

            //添加购物车
            try{
                $res = new Shopping();
                $res->user_id = $users->id;
                $res->car_brand_id = $car->car_brand_id;
                $res->car_series_id = $car->car_series_id;
                $res->car_model_id = $car->car_model_id;
                $res->user_car_info_inquiry_id = $car->id;
                $res->service_id = $service_id;
                $res->mkt_cms_id = $mkt_cms_id;
                $res->status = '1';
                $res->type = '2';
                $res->service_type = $service_type;
                $res->price = $package_arr['price'];
                $res->count_amount = $package_arr['count_amount'];
                $res->service_type = $service_type;
                $res->created_at = date("Y-m-d H:i:s",time());
                $res->updated_at = date("Y-m-d H:i:s",time());
                $res->created_by = $users->id;
                $res->updated_by = $users->id;
                $res->save();

                $response = array('code' => 0, 'msg' => 'ok');
            }catch (Exception $e){
                Log::error("error", array("system" => "api3.0" ,"event" => "addShoppingCart", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.create_service_car_error_1029");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "addShoppingCart", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-28 14:43:52
     * @Description: 清空用户购物车数据
     * @link http://www.activity.com/wechat/api3.0/del_shopping_cart?token=86ba207fc05f4586cfd87fb33231a5e0&id=3,4,5
     */
    public function del_shopping_cart(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //获取参数
            $id = Input::get('id');

            if($id == 0){
                //删除购物车当前用户的全部信息
                $shopping = Shopping::where('user_id',$users->id)->where('status',1)->update(array(
                    'status' => 2,
                    'updated_at' => date("Y-m-d H:i:s",time()),
                    'updated_by' => $users->id
                ));
            }else{
                $id = explode(',',$id);
                //删除购物车单条信息
                $shopping = Shopping::where('user_id',$users->id)->whereIn('id',$id)->update(array(
                    'status' => 2,
                    'updated_at' => date("Y-m-d H:i:s",time()),
                    'updated_by' => $users->id
                ));
            }

            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "del_shopping_cart", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:  2018-07-30 08:41:17
     * @Description: cms基础包计算价格
     */
    public function CmsPrice($car_model_id,$city_id,$id, $users){
        $response = array('code' => 0, 'msg' => 'ok','result' => '');
        $package_arr=array(
            "count_amount"=>0,
            "price"=>0,
            "discount_rate"=>1,
        );
        do{
            //基础包
            $csi=DataCarStandardInfo::find($car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.car_model_is_empty23000");
                break;
            }
            $package=ProductPackage::find($id);
            if(is_null($package)){
                $response = Lang::get("scs_error.package_error_50001");
                break;
            }
            if($package->status!=1){
                $response = Lang::get("scs_error.package_status_error_50002");
                break;
            }
//            $ppc=ProductPackageCity::where("city_id",$city_id)->where("status",1)->where("pack_id",$package->id)->first();
//            if(!$ppc){
//                $response = Lang::get("scs_error.package_unable_error_50003");
//                break;
//            }
            $p_item=ProductPackage::getItemCS5($car_model_id,$package->id);
            $whp=WorkHoursPrice::where("city_id",$city_id)->first();
            if(is_null($whp)){
                $response = Lang::get("scs_error.work_hour_error_10001");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }
            $count_amount=0;
            $supply_arr=$p_item['supply'];
            $order_product_item=array();
            foreach ($supply_arr as $_sa) {
                //更换耗材的加价系数
                $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$_sa["brand_id"])->where("supply_subject_id",$_sa["subject"])->where("status",1)->first();
                $wmcf->supply_coefficient = null;
                if (!empty($wpc)) {
                    $wpc_city=WorkPartsCoefficientCity::where('city_id',$city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                    $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                }
                if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                    $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                }
                //更换多城市价格
                // $sip=SupplyItemPrice::where("item_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->first();
                // if($sip){
                //     $_sa["amount"]=$sip->price;
                // }
                $sip=SupplyCityPrice::where("supply_id",$_sa["id"])->where("city_id",$city_id)->where("status",1)->first();
                if($sip){
                    $_sa["amount"]=$sip->price;
                }else{
                    $ss_temp=SupplySub::where("supply_id",$_sa["id"])->where("status",1)->first();
                    $_sa["amount"]=isset($ss_temp)?$ss_temp->usual_price:0;
                }
                // $c_amount=Common::upFow($si->amount*$wmcf->supply_coefficient);

                $temp_amount=$_sa["amount"]*$wmcf->supply_coefficient;
                $temp_amount=Common::upFow($temp_amount);
                $order_product_item[]=array(
                    "item_id"=>$_sa["id"],
                    "item_name"=>$_sa["name"],
                    "amount"=>$temp_amount,
                    "num"=>$_sa["number"],
                    "type"=>1,
                    "unit"=>$_sa["unit"],
                    "is_adapter"=>$_sa["is_adapter"],
                );
                $count_amount+=$temp_amount*$_sa["number"];
            }
            foreach ($p_item['server'] as $_se) {
                $res=PricingStrategy::getStringStrategy($csi->id,$_se['id'],$city_id);
                if($res['code']==0){
                    $temp_amount=$res['price'];
                }else{
                    //判断工时类型为工时类型还是固定价格
                    if($_se['type'] ==1 ){
                        $temp_amount=$whp->price*$wmcf->work_coefficient*$_se["work_hours"];
                    }elseif($_se['type']==2){
                        $temp_amount=$_se["price"];
                    }
                }
                $order_product_item[]=array(
                    "item_id"=>$_se["id"],
                    "item_name"=>$_se["name"],
                    "amount"=>$temp_amount,
                    "num"=>$_se["work_hours"],
                    "type"=>2,
                    "unit"=>"个",
                    "is_adapter"=>1,
                );
                $count_amount+=$temp_amount;
            }
//                $package_arr=array(array(
//                    "product_id"=>$package->id,
//                    "product_name"=>$package->name,
//                    "amount"=>$count_amount,
//                    "item"=>$order_product_item
//                ));

            $response=array(
                "count_amount"=>$count_amount,
                "price"=>$count_amount,
                "discount_rate"=>1,
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "CmsPrice", 'input' =>Input::all() ,"output" => $response));
        return $response;
    }


    /**
     * @Author:      sqq
     * @DateTime:  2018-07-30 08:41:17
     * @Description: cms基础包计算价格(下单时候使用)
     */
    public function OrderCmsPrice($car_model_id,$shop_id,$id, $users){
        $response = array('code' => 0, 'msg' => 'ok','result' => '');
        $package_arr=array(
            "count_amount"=>0,
            "price"=>0,
            "discount_rate"=>1,
        );
        do{
            //基础包
            $csi=DataCarStandardInfo::find($car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.car_model_is_empty23000");
                break;
            }
            $package=ProductPackage::find($id);
            if(is_null($package)){
                $response = Lang::get("scs_error.package_error_50001");
                break;
            }
            if($package->status!=1){
                $response = Lang::get("scs_error.package_status_error_50002");
                break;
            }
            $shop = MaintenanceShops::where('status',1)->where('is_show',1)->where('id',$shop_id)->first();
            if(!$shop){
                $response = Lang::get("scs_error.package_unable_error_50003");
                break;
            }
            $ppc=ProductPackageShop::where("city_id",$shop_id)->where("status",1)->where("pack_id",$package->id)->first();
            if(!$ppc){
                $response = Lang::get("scs_error.package_unable_error_50003");
                break;
            }
            $city_id = $shop->city_id;
            $p_item=ProductPackage::getItemCS5($car_model_id,$package->id);
            $whp=WorkHoursPrice::where("city_id",$city_id)->first();
            if(is_null($whp)){
                $response = Lang::get("scs_error.work_hour_error_10001");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }
            $count_amount=0;
            $supply_arr=$p_item['supply'];
            $order_product_item=array();
            foreach ($supply_arr as $_sa) {
                //更换耗材的加价系数
                $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$_sa["brand_id"])->where("supply_subject_id",$_sa["subject"])->where("status",1)->first();
                $wmcf->supply_coefficient = null;
                if (!empty($wpc)) {
                    $wpc_city=WorkPartsCoefficientCity::where('city_id',$city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                    $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                }
                if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                    $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                }
                //更换多城市价格
                // $sip=SupplyItemPrice::where("item_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->first();
                // if($sip){
                //     $_sa["amount"]=$sip->price;
                // }
                $sip=SupplyCityPrice::where("supply_id",$_sa["id"])->where("city_id",$city_id)->where("status",1)->first();
                if($sip){
                    $_sa["amount"]=$sip->price;
                }else{
                    $ss_temp=SupplySub::where("supply_id",$_sa["id"])->where("status",1)->first();
                    $_sa["amount"]=isset($ss_temp)?$ss_temp->usual_price:0;
                }
                // $c_amount=Common::upFow($si->amount*$wmcf->supply_coefficient);

                $temp_amount=$_sa["amount"]*$wmcf->supply_coefficient;
                $temp_amount=Common::upFow($temp_amount);
                $order_product_item[]=array(
                    "item_id"=>$_sa["id"],
                    "item_name"=>$_sa["name"],
                    "amount"=>$temp_amount,
                    "num"=>$_sa["number"],
                    "type"=>1,
                    "unit"=>$_sa["unit"],
                    "is_adapter"=>$_sa["is_adapter"],
                );
                $count_amount+=$temp_amount*$_sa["number"];
            }
            foreach ($p_item['server'] as $_se) {
                $res=PricingStrategy::getStringStrategy($csi->id,$_se['id'],$city_id);
                if($res['code']==0){
                    $temp_amount=$res['price'];
                }else{
                    //判断工时类型为工时类型还是固定价格
                    if($_se['type'] ==1 ){
                        $temp_amount=$whp->price*$wmcf->work_coefficient*$_se["work_hours"];
                    }elseif($_se['type']==2){
                        $temp_amount=$_se["price"];
                    }
                }
                $order_product_item[]=array(
                    "item_id"=>$_se["id"],
                    "item_name"=>$_se["name"],
                    "amount"=>$temp_amount,
                    "num"=>$_se["work_hours"],
                    "type"=>2,
                    "unit"=>"个",
                    "is_adapter"=>1,
                );
                $count_amount+=$temp_amount;
            }
//                $package_arr=array(array(
//                    "product_id"=>$package->id,
//                    "product_name"=>$package->name,
//                    "amount"=>$count_amount,
//                    "item"=>$order_product_item
//                ));

            $response=array(
                "count_amount"=>$count_amount,
                "price"=>$count_amount,
                "discount_rate"=>1,
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "OrderCmsPrice", 'input' =>Input::all() ,"output" => $response));
        return $response;
    }

    /**
     * @Author:      sqq
     * @DateTime:  2018-07-30 08:41:17
     * @Description: mkt活动包计算价格
     */
    public function MktPrice($car_model_id,$city_id,$id,$users){
        $response = array('code' => 0, 'msg' => 'ok','result' => '');
        $package_arr=array(
            "count_amount"=>0,
            "price"=>0,
            "discount_rate"=>1,
        );
        do{
            //活动包
            $csi=DataCarStandardInfo::find($car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.car_model_is_empty23000");
                break;
            }

            $pa = ProductActivity::find($id);

            if($pa->is_member==1){//如果是会员包 判断是不是能用
                $user=Users::find($users->id);
                $now_member=MemberOrdinary::find($user->member);
                $product_id=array();
                $mos=MemberOrdinaryServices::where("member_id",$now_member->id)->where("status",1)->get();
                foreach ($mos as $_mos) {
                    $product_id[]=$_mos->package_id;
                }
                $mtu=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                    ->leftJoin("member_temporary_services","member_temporary_services.member_id","=","member_temporary.id")
                    ->where("member_temporary_user.user_id",$user->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->select("member_temporary_services.package_id")->get();
                foreach ($mtu as $_mtu) {
                    $product_id[]=$_mtu->package_id;
                }
                if(!in_array($pa->id,$product_id)){//如果 该会员没有该产品包
                    $response = Lang::get("scs_error.order_ac_product_error_400140");
                    break;
                }
            }

            $pap=ProductActivityPackage::where('product_activity_id',$id)->select('package_id',"id")->get()->toArray();
            $whp=WorkHoursPrice::where("city_id",$city_id)->first();
            if(is_null($whp)){
                $response = Lang::get("scs_error.work_hour_error_10001");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }
            if(is_null($users)){
                $users->id = '0';
            }

            if($pa->type == 1){
                //一口价
                $response = array(
                    'count_amount' => $pa->price,
                    "price"=>$pa->price,
                    "discount_rate"=>$pa->discount,
                );
            }else{
                $response = AhpService::ProductActivity($pap,$users,$wmcf,$whp,$pa,$csi,$car_model_id,$city_id);
            }
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "MktPrice", 'input' =>Input::all() ,"output" => $response));
        return $response;
    }


    /**
     * @Author:      sqq
     * @DateTime:  2018-07-30 15:46:17
     * @Description: 购物车列表
     * @link http://www.activity.com/wechat/api3.0/shopping_list?token=86ba207fc05f4586cfd87fb33231a5e0
     */
    public function shopping_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }
            $service = [];
           //查询用户购物车中所有有效的商品
            $service['service'] = Shopping::where('user_id',$users->id)->where('status',1)->where('type',2)->select('id','car_brand_id','car_series_id','car_model_id','user_car_info_inquiry_id as car_id','mkt_cms_id','service_type','service_id','price','count_amount','user_car_info_inquiry_id')->orderBy('created_at','desc')->get()->toArray();
            if(!empty($service['service'])){
                //查询车辆信息
                $service['car_message'] = UserCarInfo::getCarStandardInfo($service['service'][0]['car_model_id']);
                if(!empty($service['car_message'])){
                    $service['car_message']->url = Config::get('config.car_brand_img_url');
                    $service['car_message']->car_brand_id = $service['car_message']->brand_name_id;
                    $service['car_message']->car_series_id = $service['car_message']->series_name_id;
                }
                if(!empty($service['service'][0]['user_car_info_inquiry_id'])){
                    $car_no = UserCarInfoInquiry::join('user_car_info','user_car_info_inquiry.user_car_info_id','=','user_car_info.id')->where('user_car_info_inquiry.id',$service['service'][0]['user_car_info_inquiry_id'])->select('user_car_info.car_no','user_car_info.is_default')->first();
                    if(!empty($car_no)){
                        //header("Content-type:text/html;charset=utf-8");
                        $service['car_message']->short_name = mb_substr($car_no['car_no'],0,1,'utf-8');
                        $service['car_message']->car_no = mb_substr($car_no['car_no'],1,20,'utf-8');
                        $service['car_message']->is_default = $car_no['is_default'];
                    }else{
                        $service['car_message']->short_name = '';
                        $service['car_message']->car_no = '';
                        $service['car_message']->is_default =  '0';
                    }
                }


                //查询服务名称及项目明细
                foreach($service['service'] as $_key => $_val){
                    if($_val['service_type'] == 1){
                        //mkt
                        $service['service'][$_key]['res'] = ProductActivity::select('id','name')->where('id',$_val['mkt_cms_id'])->first();
                        if(!empty($service['service'][$_key]['res'])){
                            //查询项目明细
                            $service['service'][$_key]['res']['desc'] = AhpServiceMktCms::join('ahp_service_mkt_cms_desc','ahp_service_mkt_cms.id','=','ahp_service_mkt_cms_desc.service_mkt_cms_id')->where('mkt_cms_id',$_val['mkt_cms_id'])->where('type',1)->where('ahp_service_mkt_cms_desc.status',1)->select('desc')->get()->toArray();
                            if(!empty($service['service'][$_key]['res']['desc'])){
                                $service['service'][$_key]['res']['desc'] = array_column($service['service'][$_key]['res']['desc'],'desc');
                            }
                        }else{
                            $service['service'][$_key]['res'] = [];
                        }

                    }else{
                        //cms
                        $service['service'][$_key]['res'] = ProductPackage::select('id','name')->where('id',$_val['mkt_cms_id'])->first();
                        if(!is_null($service['service'][$_key]['res'])){
                            $service['service'][$_key]['res']['desc'] = AhpServiceMktCms::join('ahp_service_mkt_cms_desc','ahp_service_mkt_cms.id','=','ahp_service_mkt_cms_desc.service_mkt_cms_id')->where('mkt_cms_id',$_val['mkt_cms_id'])->where('type',2)->where('ahp_service_mkt_cms_desc.status',1)->select('desc')->get()->toArray();
                            if(!is_null($service['service'][$_key]['res']['desc'])){
                                $service['service'][$_key]['res']['desc'] = array_column($service['service'][$_key]['res']['desc'],'desc');
                            }
                        }else{
                            $service['service'][$_key]['res'] = [];
                        }
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $service);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "shopping_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:  2018-07-30 11:08:17
     * @Description: 立即预约/购物车下单 [生成订单]
     * @link http://www.activity.com/wechat/api3.0/create_order?token=86ba207fc05f4586cfd87fb33231a5e0&order_type=2&short_name=%E4%BA%AC&car_no=111111&id=1,2&city=%E5%8C%97%E4%BA%AC%E5%B8%82&car_id=1&name=%E6%97%B6%E5%BA%86%E5%BA%86&phone=15910959937&book_time=2018-07-31&shop_id=1&&book_hour=2018-07-31&book_hour_id=3&order_source=1&is_app=1
     */
    public function create_order(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_type' => 'required',
                'short_name' => 'required',
                'car_no' => 'required',
                'city' => 'required',
                'name' => 'required',
                'phone' => 'required',
                'book_time' => 'required',
                'shop_id' => 'required',
                'book_hour' => 'required',
                'book_hour_id' => 'required',
                'order_source' => 'required',
                'is_app' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //获取参数
            $order_type = Input::get('order_type');
            $id = Input::get('id');
            $city_name = Input::get('city');
            $short_name = Input::get('short_name');
            $car_no = Input::get('car_no');
            $shop_id = Input::get('shop_id');
            $book_time = Input::get('book_time');
            $book_hour = Input::get('book_hour');
            $book_hour_id = Input::get('book_hour_id');
            $name = Input::get('name');
            $phone= Input::get('phone');
            $remarks= Input::get('remarks');
            $order_source= Input::get('order_source');
            $is_call= Input::get('is_call',1);
            //立即下单
            $car_id = Input::get('car_id');
            $service_id = Input::get('service_id');
            $mkt_cms_id = Input::get('mkt_cms_id');
            $service_type = Input::get('service_type');
            $car_model_id = Input::get('car_model_id');
            $car_brand_id = Input::get('car_brand_id');
            $car_series_id = Input::get('car_series_id');

            //判断城市是否开放
            $city_id = PublicApi::Judge_city($city_name);
            if($city_id == 0){
                //城市未开放
                $response = Lang::get("error.service_list_city_empty_error_30011");
                break;
            }

            $original_price = '0';
            $pay_price = '0';
            $discount_rate = '1';

            $now_member=MemberOrdinary::find($users->member);
            $now_data=UserMember::where("user_id",$users->id)->where("member",$users->member)->orderBy("created_at","desc")->first();
            $pt_member['dis']=isset($now_member->dis) ? $now_member->dis:1;
            $pt_member['created_at']=isset($now_data->created_at) ? $now_data->created_at :'';
            $pt_member['relation']='无';
            $pt_member['type']=3;
            $mtu_member=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                ->where("member_temporary_user.user_id",$users->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->orderBy("member_temporary.dis","asc")->select("member_temporary.dis","member_temporary_user.created_at")->first();

            $ls_member['dis']=isset($mtu_member->dis) ? $mtu_member->dis:1;
            $ls_member['created_at']=isset($mtu_member->created_at) ? $mtu_member->created_at :'';
            $ls_member['relation']='无';
            $ls_member['type']=4;

            if($pt_member['dis']<=$ls_member['dis']){
                $arr[]=$pt_member;
            }else{
                $arr[]=$ls_member;
            }
            foreach($arr as $key=>$_arr){
                $dis[$key]=$_arr['dis'];
                $created_at[$key]=$_arr['created_at'];
            }
            array_multisort($dis, SORT_ASC, $created_at, SORT_DESC, $arr);
            $dis_arr=$arr[0];
            $dis_last['dis']=$dis_arr['dis'];
            $dis_last['relation']=$dis_arr['relation'];
            $dis_last['type']=$dis_arr['type'];

            if($order_type == 1){
                //立即下单
                if((isset($car_id) && $car_id == '') || !isset($car_id)){
                    $response = Lang::get("error.create_order_car_id_empty_error_1025");
                    break;
                }
                if((isset($service_id) && $service_id == '') || !isset($service_id)){
                    $response = Lang::get("error.create_order_service_id_empty_error_1026");
                    break;
                }
                if((isset($mkt_cms_id) && $mkt_cms_id == '') || !isset($mkt_cms_id)){
                    $response = Lang::get("error.create_order_mkt_cms_id_empty_error_1027");
                    break;
                }
                if((isset($service_type) && $service_type == '') || !isset($service_type)){
                    $response = Lang::get("error.create_order_service_type_empty_error_1028");
                    break;
                }

                $data = array(array('id' => $mkt_cms_id, 'service_type' => $service_type));
                $data = json_encode($data);
                $shop_s = AhpService::city_shop($data, $users);

                if(!in_array($shop_id,$shop_s['id'])){
                    $response = Lang::get("error.service_shopping_car_not_in_shop_error_1031");
                    break;
                }

                //判断是基础包还是活动包
                if($service_type == 1){
                    $package_arr = $this->MktPrice($car_model_id,$city_id,$mkt_cms_id,$users);
                }else{
                    $package_arr = $this->OrderCmsPrice($car_model_id,$shop_id,$mkt_cms_id,$users);
                }
                if(!empty($package_arr) && array_key_exists('code',$package_arr)){
                    return json_encode($package_arr);break;
                }

                if($service_type == 2){
                    $pay_price = $package_arr['count_amount'] * $dis_last['dis'];
                }else{
                    $pay_price = $package_arr['count_amount'];
                }
                $original_price = $package_arr['price'];
                $discount_price = $original_price - $pay_price;
                $price =[
                    'pay_price' => $pay_price,  //应付金额
                    'original_price' => $original_price,  //实际金额
                    'discount_price' => $discount_price,  // 优惠金额
                    'discount_rate' => $dis_last['dis'] ? $dis_last['dis'] : 1  //折扣
                ];

            }else{
                //购物车下单
                if($id){
                    $id = explode(',',$id);
                    $id = array_filter($id);
                    //根据id计算价格

                    $es = Shopping::whereIn('id',$id)->where('status',1)->where('type',2)->where('user_id',$users->id)->get();
                    $data = [];
                    foreach($es as $e_k => $e_v){
                        $data[] =[
                            'id' => $e_v->mkt_cms_id,
                            'service_type' => $e_v->service_type,
                        ];
                    }
                    $data = json_encode($data);
                    $shop_s = AhpService::city_shop($data, $users);
                    if(!in_array($shop_id,$shop_s['id'])){
                        $response = Lang::get("error.service_shopping_car_not_in_shop_error_1031");
                        break;
                    }

                    $discount_price = '0';
                    foreach($id as $_id){
                        //根据购物车id，查询服务id和类型
                        $service = Shopping::where('id',$_id)->where('status',1)->where('type',2)->where('user_id',$users->id)->first();
                        if(is_null($service)){
                            $response = array("code" => 1024, "msg" => '服务id：'.$_id."未加入购物车");
                            return json_encode($response);
                            break;
                        }else{
                            //判断是基础包还是活动包
                            if($service->service_type == 1){
                                $package_arr = $this->MktPrice($service->car_model_id,$city_id,$service->mkt_cms_id,$users);
                                $names = ProductActivity::find($service->mkt_cms_id);
                            }else{
                                $package_arr = $this->OrderCmsPrice($service->car_model_id,$shop_id,$service->mkt_cms_id,$users);
                                $names = ProductPackage::find($service->mkt_cms_id);
                            }

                            if($package_arr && array_key_exists('code',$package_arr)){
                                return json_encode($package_arr);break;
                            }

                            if(empty($names)){
                                $names = (object)[];
                                $names->name = '';
                            }
                            if((int)($package_arr['price']) != (int)($service->price)){
                                $response = array("code" => 1029, "msg" => '服务：'.$names->name."价格有变，请重新添加");
                                return json_encode($response);
                                break;
                            }
                            //count_amount 是会员价
                            if($service->service_type == 2){
                                $pay_price += $package_arr['count_amount'] * $dis_last['dis'];
                            }else{
                                $pay_price += $package_arr['count_amount'];  //应付金额
                            }
                            $original_price += $package_arr['price'];  //实际金额
                        }
                    }
                    $discount_price = $original_price - $pay_price;  //应付金额
                    $price =[
                        'pay_price' => $pay_price,   //应付金额
                        'original_price' => $original_price, //原价
                        'discount_price' => $discount_price,  //优惠金额
                        'discount_rate' => $dis_last['dis'] ? $dis_last['dis'] : 1
                    ];

                    //$response = array('code' => 0, 'msg' => 'ok', 'result' => $response);
                }else{
                    $response = Lang::get("error.user_car_choose_buy_error_1023");
                    break;
                }
            }
            header("Content-type:text/html;charset=utf-8");
            //生成订单流程
            $order_id = Common::createOrderId();
            if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $short_name)<=0){
                return json_encode(array('code' => 100332, 'msg' => '车牌号首字符不是中文'));break;
            }
            //检测是否重复下单
            if(Orders::createOrderCheck3($short_name.$car_no,$shop_id)){
                $response = Lang::get("error.order_ing_error_40003");
                break;
            }
            $ms = MaintenanceShops::where('id',$shop_id)->where('status',1)->first();
            if(is_null($ms)){
                $response = Lang::get("error.order_shop_msg_error_40005");
                break;
            }
            //$user_auth_car = UserAuthenticationCar::where('car_no',$short_name.$car_no)->where('status',1)->first();
            $user_auth_car = UserCarInfo::where('car_no',$short_name.$car_no)->where('status',1)->first();
            $car_brand_id = $car_series_id = $car_model_id = $user_car_id = 0;
            $car_brand_name = $car_series_name = $car_model_name = "";
            if(!is_null($user_auth_car)){
                $car_brand_id = $user_auth_car->car_brand_id;
                $car_series_id = $user_auth_car->car_series_id;
                $car_model_id = $user_auth_car->car_model_id;
                $csi = DataCarStandardInfo::find($car_model_id);
                if($csi){
                    $car_brand_name = $csi->brand_name;
                    $car_series_name = $csi->series_name;
                    $car_model_name = $csi->model_name;
                }
                $uci = UserCarInfo::where('user_id',$users->id)->where('car_no',$short_name.$car_no)->where('status',1)->first();
                if($uci){
                    $user_car_id = $uci->id;
                }
            }
            $status = Config::get('order.system_confirm_order_status');
            if($book_time == date('Y-m-d',time())){
                $status = Config::get('order.system_confirm_order_status');
            }

            $shop = MaintenanceShops::where('status',1)->where('is_show',1)->where('id',$shop_id)->first();
            if(!$shop){
                $response = Lang::get("scs_error.package_unable_error_50003");
                break;
            }
            $city_id = $shop->city_id;
            DB::beginTransaction();
            $orders = new Orders();
            $orders->order_id = $order_id;
            $orders->user_id = $users->id;
            $orders->city = $city_id;
            $orders->place = 2;
            $orders->book_time = $book_time;
            $orders->book_hour = $book_hour;
            $orders->shop_id =  isset($shop_id)?$shop_id:0;
            $orders->address =  "";
            $orders->name = $name;
            $orders->tittle = "";
            $orders->phone = $phone;
            $orders->pay_type = 1;
            $orders->user_car_id = $user_car_id;
            $orders->amount = $original_price;    //订单金额
            $orders->work_service = 0;
            $orders->status = $status;
            $orders->note = isset($remarks)?$remarks:"";
            $orders->created_at = Common::num2DateTime(time());
            $orders->car_brand_id = $car_brand_id;
            $orders->car_brand_name = $car_brand_name;
            $orders->car_series_id = $car_series_id;
            $orders->car_series_name = $car_series_name;
            $orders->car_model_id = $car_model_id;
            $orders->car_model_name = $car_model_name;
            $orders->car_no = $short_name.$car_no;
            $orders->outer_order_id = 0;
            $orders->engineer_id = 0;
            $orders->car_id = 0;
            $orders->mileage = 0;
            $orders->oil_meter = 0;
            $orders->order_source = $order_source;//10-微站 2-app
            $orders->product_comment = "";
            //$orders->discount_amount = $discount_price;   //优惠券优惠金额
            $orders->balance_amount = $pay_price;    //应收金额
            $orders->discount = $discount_price;    //应收金额
            $orders->discount_rate = $dis_last['dis'];    //应收金额
            $orders->is_call = $is_call;
            $orders->save();

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order_id;
            $order_flows->status = $status;
            $order_flows->user_id = $users->id;
            $order_flows->type = 'custom';
            $order_flows->created_at = Common::num2DateTime(time());
            $order_flows->save();

            $order_maintenance = new OrderMaintence();
            $order_maintenance->boot_date = $book_time;
            $order_maintenance->order_id = $order_id;
            $order_maintenance->maintenance_type = 'shop';
            $order_maintenance->maintenance_id = isset($shop_id)?$shop_id:0; //如果type是car 上门车还没分配 不知道是谁 所以存0 如果是shop 即门店id
            $order_maintenance->time_prat_id = $book_hour_id;
            $order_maintenance->save();

            $service_type_name = "";
            $order_service_types = Input::get('order_service_type');
            if($order_service_types){
                $arr_id = explode(',',rtrim($order_service_types,','));
                if(count($arr_id)){
                    foreach($arr_id as $_a){
                        $ot = new OrderType();
                        $ot->order_id = $order_id;
                        $ot->order_type = $_a;
                        $ot->save();
                        $service_type_name .= Orders::$service_type[$_a].'/';
                    }
                }
            }

            try{
                if($order_type == 1){
                    //购物车表生成临时数据
                    $res = new Shopping();
                    $res->user_id = $users->id;
                    $res->order_id = $order_id;
                    $res->shop_id = isset($shop_id)?$shop_id:0;
                    $res->car_brand_id = $car_brand_id;
                    $res->car_series_id = $car_series_id;
                    $res->car_model_id = $car_model_id;
                    $res->user_car_info_inquiry_id = $car_id;
                    $res->service_id = $service_id;
                    $res->mkt_cms_id = $mkt_cms_id;
                    $res->status = '3';
                    $res->type = $order_type;
                    $res->service_type = $service_type;
                    $res->created_at = date("Y-m-d H:i:s",time());
                    $res->updated_at = date("Y-m-d H:i:s",time());
                    $res->created_by = $users->id;
                    $res->updated_by = $users->id;
                    $res->price = $original_price;
                    $res->count_amount = $original_price - $discount_price;
                    $res->save();
                }else{
                    //生成订单成功，修改购物车表状态
                    $data = array(
                        'order_id' => $order_id,
                        'shop_id' => $orders->shop_id,
                        'status' => '3',
                        'updated_at' => date("Y-m-d H:i:s",time()),
                        'updated_by' => $users->id
                    );
                    $id = explode(',',Input::get('id'));
                    $id = array_filter($id);
                    $shopping = new Shopping();
                    $shopping->where('user_id',$users->id)->whereIn('id',$id)->update($data);
                }
            }catch(Exception $e){
                Log::error("error", array("system" => "api3.0" ,"event" => "create_order", 'input' =>Input::all() ,"exception" => $e));
                DB::rollBack();
                $response = array('code' => -1, 'msg' => '修改购物车失败');
                break;
            }

            try{
                if($order_type ==1){ //立即下单
                    if($service_type == 1){ //mkt 活动包
                        $orders=Orders::find($order_id);
                        $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();
                        $csi=DataCarStandardInfo::find($orders->car_model_id);
                        $pa = ProductActivity::find($mkt_cms_id);
                        if($pa->is_member==1){//如果是会员包 判断是不是能用
                            $user=Users::find($orders->user_id);
                            $now_member=MemberOrdinary::find($user->member);
                            $product_id=array();
                            $mos=MemberOrdinaryServices::where("member_id",$now_member->id)->where("status",1)->get();
                            foreach ($mos as $_mos) {
                                $product_id[]=$_mos->package_id;
                            }
                            $mtu=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                                ->leftJoin("member_temporary_services","member_temporary_services.member_id","=","member_temporary.id")
                                ->where("member_temporary_user.user_id",$user->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->select("member_temporary_services.package_id")->get();
                            foreach ($mtu as $_mtu) {
                                $product_id[]=$_mtu->package_id;
                            }
                            if(!in_array($pa->id,$product_id)){//如果 该会员没有该产品包
                                DB::rollBack();
                                $response = Lang::get("scs_error.order_ac_product_error_400140");
                                break;
                            }
                        }
                        $pap=ProductActivityPackage::where('product_activity_id',$mkt_cms_id)->select('package_id',"id")->get()->toArray();
                        $whp=WorkHoursPrice::where("city_id",$city_id)->first();
                        if(is_null($whp)){
                            DB::rollBack();
                            $response = Lang::get("scs_error.work_hour_error_10001");
                            break;
                        }

                        $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
                        if(is_null($wmcf)){
                            DB::rollBack();
                            $response = Lang::get("scs_error.work_mcf_error_10002");
                            break;
                        }
                        $response=AhpService::addProductActivity($pap,$users,$orders,$wmcf,$whp,$pa,$csi,$city_id);
                    }
                    if($service_type == 2){
                        $orders=Orders::find($order_id);
                        if(is_null($orders)){
                            DB::rollBack();
                            $response = Lang::get("scs_error.order_notexiet_40000");
                            break;
                        }
                        if($orders->order_type==1){
                            if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                                DB::rollBack();
                                $response = Lang::get("scs_error.order_status_error_40022");
                                break;
                            }
                        }else{
                            if($orders->status!=1411){//订单状态是正确
                                DB::rollBack();
                                $response = Lang::get("scs_error.order_status_error_40022");
                                break;
                            }
                        }
                        $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();
                        if($op){//订单状态是否为服务结束状态
                            DB::rollBack();
                            $response = Lang::get("scs_error.order_pay_record_40112");
                            break;
                        }
                        $op=OrderPerformance::where('order_id',$order_id)->first();
                        if($op){//如果存在检测记录
                            if(date("Y-m",strtotime($op->created_at))!=date("Y-m",time())){
                                DB::rollBack();
                                $response = Lang::get("scs_error.order_checek_time_error_40079");
                                break;
                            }
                        }


                        $csi=DataCarStandardInfo::find($orders->car_model_id);
                        if(is_null($csi)){
                            DB::rollBack();
                            $response = Lang::get("scs_error.car_model_is_empty23000");
                            break;
                        }
                        $package=ProductPackage::find($mkt_cms_id);
                        if(is_null($package)){
                            DB::rollBack();
                            $response = Lang::get("scs_error.package_error_50001");
                            break;
                        }
                        if($package->status!=1){
                            DB::rollBack();
                            $response = Lang::get("scs_error.package_status_error_50002");
                            break;
                        }
                        // $ppc=ProductPackageCity::where("city_id",$orders->city)->where("status",1)->where("pack_id",$package->id)->first();
                        $ppc=ProductPackageShop::isShopPackage($orders->shop_id,$package->id);
                        if(!$ppc){
                            DB::rollBack();
                            $response = Lang::get("scs_error.package_unable_error_50003");
                            break;
                        }
                        // if($package->city!=$sc_user->shop->city_id){
                        //     $response = Lang::get("scs_error.package_unable_error_50003");
                        //     break;
                        // }
                        $p_item=ProductPackage::getItemCS5($orders->car_model_id,$package->id);
                        $whp=WorkHoursPrice::where("city_id",$city_id)->first();
                        if(is_null($whp)){
                            DB::rollBack();
                            $response = Lang::get("scs_error.work_hour_error_10001");
                            break;
                        }
                        $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
                        if(is_null($wmcf)){
                            DB::rollBack();
                            $response = Lang::get("scs_error.work_mcf_error_10002");
                            break;
                        }
                        $count_amount=0;
                        $supply_arr=$p_item['supply'];
                        $order_product_item=array();
                        foreach ($supply_arr as $_sa) {
                            //更换耗材的加价系数
                            $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$_sa["brand_id"])->where("supply_subject_id",$_sa["subject"])->where("status",1)->first();
                            $wmcf->supply_coefficient = null;
                            if (!empty($wpc)) {
                                $wpc_city=WorkPartsCoefficientCity::where('city_id',$city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                                $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                            }
                            if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                                $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                            }
                            //更换多城市价格
                            // $sip=SupplyItemPrice::where("item_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->first();
                            // if($sip){
                            //     $_sa["amount"]=$sip->price;
                            // }

                            $sip=SupplyCityPrice::where("supply_id",$_sa["id"])->where("city_id",$orders->city)->where("status",1)->first();
                            if($sip){
                                $_sa["amount"]=$sip->price;
                            }else{
                                $ss_temp=SupplySub::where("supply_id",$_sa["id"])->where("status",1)->first();
                                $_sa["amount"]=isset($ss_temp)?$ss_temp->usual_price:0;
                            }
                            // $c_amount=Common::upFow($si->amount*$wmcf->supply_coefficient);

                            $temp_amount=$_sa["amount"]*$wmcf->supply_coefficient;
                            $temp_amount=Common::upFow($temp_amount);
                            $order_product_item[]=array(
                                "item_id"=>$_sa["id"],
                                "item_name"=>$_sa["name"],
                                "amount"=>$temp_amount,
                                "num"=>$_sa["number"],
                                "type"=>1,
                                "unit"=>$_sa["unit"],
                                "is_adapter"=>$_sa["is_adapter"],
                            );
                            $count_amount+=$temp_amount*$_sa["number"];
                        }
                        foreach ($p_item['server'] as $_se) {
                            $res=PricingStrategy::getStringStrategy($csi->id,$_se['id'],$city_id);
                            if($res['code']==0){
                                $temp_amount=$res['price'];
                            }else{
                                //判断工时类型为工时类型还是固定价格
                                if($_se['type'] ==1 ){
                                    $temp_amount=$whp->price*$wmcf->work_coefficient*$_se["work_hours"];
                                }elseif($_se['type']==2){
                                    $temp_amount=$_se["price"];
                                }
                            }
                            $order_product_item[]=array(
                                "item_id"=>$_se["id"],
                                "item_name"=>$_se["name"],
                                "amount"=>$temp_amount,
                                "num"=>$_se["work_hours"],
                                "type"=>2,
                                "unit"=>"个",
                                "is_adapter"=>1,
                            );
                            $count_amount+=$temp_amount;
                        }

                        if($service_type == 2){
                            $now_member=MemberOrdinary::find($users->member);
                            $now_data=UserMember::where("user_id",$users->id)->where("member",$users->member)->orderBy("created_at","desc")->first();
                            $pt_member['dis']=isset($now_member->dis) ? $now_member->dis:1;
                            $pt_member['created_at']=isset($now_data->created_at) ? $now_data->created_at :'';
                            $pt_member['relation']='无';
                            $pt_member['type']=3;
                            $mtu_member=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                                ->where("member_temporary_user.user_id",$users->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->orderBy("member_temporary.dis","asc")->select("member_temporary.dis","member_temporary_user.created_at")->first();

                            $ls_member['dis']=isset($mtu_member->dis) ? $mtu_member->dis:1;
                            $ls_member['created_at']=isset($mtu_member->created_at) ? $mtu_member->created_at :'';
                            $ls_member['relation']='无';
                            $ls_member['type']=4;

                            if($pt_member['dis']<=$ls_member['dis']){
                                $arr[]=$pt_member;
                            }else{
                                $arr[]=$ls_member;
                            }
                            foreach($arr as $key=>$_arr){
                                $dis[$key]=$_arr['dis'];
                                $created_at[$key]=$_arr['created_at'];
                            }
                            array_multisort($dis, SORT_ASC, $created_at, SORT_DESC, $arr);
                            $dis_arr=$arr[0];
                            $dis_last['dis']=$dis_arr['dis'];
                            $dis_last['relation']=$dis_arr['relation'];
                            $dis_last['type']=$dis_arr['type'];
                        }else{
                            $dis_last['dis'] = 1;
                        }

                        $package_arr=array(array(
                            "product_id"=>$package->id,
                            "product_name"=>$package->name,
                            "amount"=>$count_amount,
                            "item"=>$order_product_item,
                            'discount_rate'=>$dis_last['dis']
                        ));
                        $response = AhpService::saveBaseProducts($package_arr,"",$users->id,$orders->order_id);
                    }
                }else{
                    //购物车
                    $activity_id = Shopping::where('order_id',$order_id)->select('order_id','service_type','mkt_cms_id')->where('status',3)->get();
                    if(!is_null($activity_id)){
                        foreach($activity_id as $key => $val){
                            if($val->service_type == 1){
                                $orders=Orders::find($order_id);
                                $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();
                                $csi=DataCarStandardInfo::find($orders->car_model_id);
                                $pa = ProductActivity::find($val['mkt_cms_id']);
                                if($pa->is_member==1){//如果是会员包 判断是不是能用
                                    $user=Users::find($orders->user_id);
                                    $now_member=MemberOrdinary::find($user->member);
                                    $product_id=array();
                                    $mos=MemberOrdinaryServices::where("member_id",$now_member->id)->where("status",1)->get();
                                    foreach ($mos as $_mos) {
                                        $product_id[]=$_mos->package_id;
                                    }
                                    $mtu=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                                        ->leftJoin("member_temporary_services","member_temporary_services.member_id","=","member_temporary.id")
                                        ->where("member_temporary_user.user_id",$user->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->select("member_temporary_services.package_id")->get();
                                    foreach ($mtu as $_mtu) {
                                        $product_id[]=$_mtu->package_id;
                                    }
                                    if(!in_array($pa->id,$product_id)){//如果 该会员没有该产品包
                                        DB::rollBack();
                                        $response = Lang::get("scs_error.order_ac_product_error_400140");
                                        break;
                                    }
                                }

                                $pap=ProductActivityPackage::where('product_activity_id',$val['mkt_cms_id'])->select('package_id',"id")->get()->toArray();
                                $whp=WorkHoursPrice::where("city_id",$city_id)->first();
                                if(is_null($whp)){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.work_hour_error_10001");
                                    break;
                                }
                                $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
                                if(is_null($wmcf)){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.work_mcf_error_10002");
                                    break;
                                }
                                $response=AhpService::addProductActivity($pap,$users,$orders,$wmcf,$whp,$pa,$csi,$city_id);
                            }else{
                                $orders=Orders::find($order_id);
                                if(is_null($orders)){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.order_notexiet_40000");
                                    break;
                                }
                                if($orders->order_type==1){
                                    if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                                        DB::rollBack();
                                        $response = Lang::get("scs_error.order_status_error_40022");
                                        break;
                                    }
                                }else{
                                    if($orders->status!=1411){//订单状态是正确
                                        DB::rollBack();
                                        $response = Lang::get("scs_error.order_status_error_40022");
                                        break;
                                    }
                                }
                                $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();
                                if($op){//订单状态是否为服务结束状态
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.order_pay_record_40112");
                                    break;
                                }
                                $op=OrderPerformance::where('order_id',$order_id)->first();
                                if($op){//如果存在检测记录
                                    if(date("Y-m",strtotime($op->created_at))!=date("Y-m",time())){
                                        DB::rollBack();
                                        $response = Lang::get("scs_error.order_checek_time_error_40079");
                                        break;
                                    }
                                }


                                $csi=DataCarStandardInfo::find($orders->car_model_id);
                                if(is_null($csi)){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.car_model_is_empty23000");
                                    break;
                                }
                                $package=ProductPackage::find($val['mkt_cms_id']);
                                if(is_null($package)){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.package_error_50001");
                                    break;
                                }
                                if($package->status!=1){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.package_status_error_50002");
                                    break;
                                }
                                // $ppc=ProductPackageCity::where("city_id",$orders->city)->where("status",1)->where("pack_id",$package->id)->first();
                                $ppc=ProductPackageShop::isShopPackage($orders->shop_id,$package->id);
                                if(!$ppc){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.package_unable_error_50003");
                                    break;
                                }
                                // if($package->city!=$sc_user->shop->city_id){
                                //     $response = Lang::get("scs_error.package_unable_error_50003");
                                //     break;
                                // }
                                $p_item=ProductPackage::getItemCS5($orders->car_model_id,$package->id);
                                $whp=WorkHoursPrice::where("city_id",$city_id)->first();
                                if(is_null($whp)){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.work_hour_error_10001");
                                    break;
                                }
                                $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
                                if(is_null($wmcf)){
                                    DB::rollBack();
                                    $response = Lang::get("scs_error.work_mcf_error_10002");
                                    break;
                                }
                                $count_amount=0;
                                $supply_arr=$p_item['supply'];
                                $order_product_item=array();
                                foreach ($supply_arr as $_sa) {
                                    //更换耗材的加价系数
                                    $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$_sa["brand_id"])->where("supply_subject_id",$_sa["subject"])->where("status",1)->first();
                                    $wmcf->supply_coefficient = null;
                                    if (!empty($wpc)) {
                                        $wpc_city=WorkPartsCoefficientCity::where('city_id',$city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                                        $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                                    }
                                    if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                                        $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                                    }
                                    //更换多城市价格
                                    // $sip=SupplyItemPrice::where("item_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->first();
                                    // if($sip){
                                    //     $_sa["amount"]=$sip->price;
                                    // }

                                    $sip=SupplyCityPrice::where("supply_id",$_sa["id"])->where("city_id",$orders->city)->where("status",1)->first();
                                    if($sip){
                                        $_sa["amount"]=$sip->price;
                                    }else{
                                        $ss_temp=SupplySub::where("supply_id",$_sa["id"])->where("status",1)->first();
                                        $_sa["amount"]=isset($ss_temp)?$ss_temp->usual_price:0;
                                    }
                                    // $c_amount=Common::upFow($si->amount*$wmcf->supply_coefficient);

                                    $temp_amount=$_sa["amount"]*$wmcf->supply_coefficient;
                                    $temp_amount=Common::upFow($temp_amount);
                                    $order_product_item[]=array(
                                        "item_id"=>$_sa["id"],
                                        "item_name"=>$_sa["name"],
                                        "amount"=>$temp_amount,
                                        "num"=>$_sa["number"],
                                        "type"=>1,
                                        "unit"=>$_sa["unit"],
                                        "is_adapter"=>$_sa["is_adapter"],
                                    );
                                    $count_amount+=$temp_amount*$_sa["number"];
                                }
                                foreach ($p_item['server'] as $_se) {
                                    $res=PricingStrategy::getStringStrategy($csi->id,$_se['id'],$city_id);
                                    if($res['code']==0){
                                        $temp_amount=$res['price'];
                                    }else{
                                        //判断工时类型为工时类型还是固定价格
                                        if($_se['type'] ==1 ){
                                            $temp_amount=$whp->price*$wmcf->work_coefficient*$_se["work_hours"];
                                        }elseif($_se['type']==2){
                                            $temp_amount=$_se["price"];
                                        }
                                    }
                                    $order_product_item[]=array(
                                        "item_id"=>$_se["id"],
                                        "item_name"=>$_se["name"],
                                        "amount"=>$temp_amount,
                                        "num"=>$_se["work_hours"],
                                        "type"=>2,
                                        "unit"=>"个",
                                        "is_adapter"=>1,
                                    );
                                    $count_amount+=$temp_amount;
                                }

                                if($val->service_type == 2){
                                    $now_member=MemberOrdinary::find($users->member);
                                    $now_data=UserMember::where("user_id",$users->id)->where("member",$users->member)->orderBy("created_at","desc")->first();
                                    $pt_member['dis']=isset($now_member->dis) ? $now_member->dis:1;
                                    $pt_member['created_at']=isset($now_data->created_at) ? $now_data->created_at :'';
                                    $pt_member['relation']='无';
                                    $pt_member['type']=3;
                                    $mtu_member=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                                        ->where("member_temporary_user.user_id",$users->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->orderBy("member_temporary.dis","asc")->select("member_temporary.dis","member_temporary_user.created_at")->first();

                                    $ls_member['dis']=isset($mtu_member->dis) ? $mtu_member->dis:1;
                                    $ls_member['created_at']=isset($mtu_member->created_at) ? $mtu_member->created_at :'';
                                    $ls_member['relation']='无';
                                    $ls_member['type']=4;

                                    if($pt_member['dis']<=$ls_member['dis']){
                                        $arr[]=$pt_member;
                                    }else{
                                        $arr[]=$ls_member;
                                    }
                                    foreach($arr as $key=>$_arr){
                                        $dis[$key]=$_arr['dis'];
                                        $created_at[$key]=$_arr['created_at'];
                                    }
                                    array_multisort($dis, SORT_ASC, $created_at, SORT_DESC, $arr);
                                    $dis_arr=$arr[0];
                                    $dis_last['dis']=$dis_arr['dis'];
                                    $dis_last['relation']=$dis_arr['relation'];
                                    $dis_last['type']=$dis_arr['type'];
                                }else{
                                    $dis_last['dis'] = 1;
                                }

                                $package_arr=array(array(
                                    "product_id"=>$package->id,
                                    "product_name"=>$package->name,
                                    "amount"=>$count_amount,
                                    "item"=>$order_product_item,
                                    'discount_rate'=>$dis_last['dis']
                                ));
                                $response = AhpService::saveBaseProducts($package_arr,"",$users->id,$orders->order_id);
                            }
                        }
                    }
                }
            }catch(Exception $e){
                Log::error("error", array("system" => "api3.0", "event" => "create_order", 'input' => Input::all(), "exception" => $e));
                DB::rollBack();
                $response = array('code' => -1, 'msg' => '保存服务失败');
                break;
            }

            DB::commit();

            try{
                //统计
                $all_order = Shopping::where('order_id',$order_id)->get();
                if(!is_null($all_order)){
                    foreach($all_order as $a_key => $a_val){
                        $product = AhpServiceStatistics::where('service_type',$a_val->service_type)->where('product_id',$a_val->mkt_cms_id)->first();
                        if(is_null($product)){
                            $product = new AhpServiceStatistics();
                            $product->service_type = $a_val->service_type;
                            $product->product_id = $a_val->mkt_cms_id;
                            $product->num = 1;
                            $product->created_at = Common::currentTimeString();
                            $product->updated_at = Common::currentTimeString();
                            $product->save();
                        }else{
                            AhpServiceStatistics::where('service_type',$a_val->service_type)->where('product_id',$a_val->mkt_cms_id)->update(array('num' => $product->num + 1, 'updated_at' => Common::currentTimeString()));
                        }
                        AhpService::where('id',$a_val->service_id)->increment('num',1);
                    }
                }
            }catch(Exception $e){
                Log::error("error", array("system" => "api3.0" ,"event" => "create_order", 'input' =>Input::all() ,"exception" => $e));
                //DB::rollBack();
                $response = array('code' => -22222, 'msg' => '下单统计失败');
//                break;
            }


            try {
                NewsLog::NewsPush($users->id,$order_id,1,0,'订单已确认','您的订单已确认，请准时到达门店哦。');
            } catch (Exception $e) {
                Log::error("error", array("system" => "api3.0" ,"event" => "create_order", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.run_exception");
//                break;
            }

            if(Config::get('u_meng_push.is_open_u_meng_push') ==1 && Input::get('is_app') ==1){
                Orders::notifyUserOrderStatus($users->id,$order_id,'订单已确认','您的订单已确认，请准时到达门店哦。');
            }

            if(Input::get('is_app') != 1) { //1-代表app 2-微站
                try {
                    if ($orders->is_call == 1) {
                        $is_call = '需要门店回电';
                    } else {
                        $is_call = '';
                    }
                    $shop = MaintenanceShops::where('id', $orders->shop_id)->first();
                    $templateId = Config::get('config.templateId');
                    $url = Config::get('config.redirect_url') . '/order/show?is_wash=0&order_id=' . $order_id;
                    $data = array(
                        "first" => "亲爱的车主您好，您的预约已提交成功，欢迎您届时光临。",
                        "keyword1" => date("m", strtotime($orders->book_time)) . '月' . date('d', strtotime($orders->book_time)) . '日',
                        "keyword2" => $orders->car_no . "  " . trim($service_type_name . $is_call, '/'),
                        "keyword3" => $shop->name,
                        "keyword4" => $shop->tel_phone,
                        "keyword5" => $shop->address,
                        "remark" => "到店后，请提供预约车牌号，点击查看详情"
                    );
                    WechatOauthController::sendMessage($users->openid, $templateId, $data, $url);

                } catch (Exception $e) {
                    Log::error("error", array("system" => "api3.0", "event" => "create_order", 'input' => Input::all(), "exception" => $e));
                    //$response = Lang::get("error.order_create_msg_error_40004");
                    //break;
                }
            }

            $response = array('order_id' => $order_id);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $response);
            //$response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "create_order", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-09-01 15:08:52
     * @Description: 下单页面门店列表
     * @link
     */
        public function shopList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'data' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //获取参数
            $data = Input::get('data');
            //$result = AhpService::city_shop($data, $users);

            //查询购物车是否有当前用户的商品
//            $es = Shopping::where('status',1)->where('type',2)->where('user_id',$users->id)->get();
//            if(is_null($es)){
//                $response = Lang::get("error.user_car_choose_buy_error_1023");
//                break;
//            }
            //$data = [];
            $shops = [];
            $aas = [];
            $jiaoji = [];
            $ji_first = [];
            if(!is_null($data)){
//                foreach($es as $e_k => $e_v){
//                    $data[] =[
//                        'id' => $e_v->mkt_cms_id,
//                        'service_type' => $e_v->service_type,
//                    ];
//                }
                $data = json_decode($data);
                if(sizeof($data) > 1){
                    foreach($data as $k => $v){
                        $a = array($v);
                        $data = json_encode($a);
                        $aas[] = AhpService::city_shop($data, $users);
                        foreach($aas as $_k => $_v){
                            if($k == 0){
                                $ji_first = $_v['id'];
                                $jiaoji = $ji_first;
                            }else{
                                $jiaoji = array_intersect($jiaoji, $_v['id']);
//                                if(empty($jiaoji)){
//                                    if($v['service_type'] == 1){
//                                        $product = ProductActivity::where('id',$v['id'])->select('name')->first();
//                                    }else{
//                                        $product = ProductPackage::where('id',$v['id'])->select('name')->first();
//                                    }
//                                    //$response = Lang::get("error.service_shopping_car_not_in_shop_error_1031");
//                                    $response = array('code' => 1031, 'msg' => '购物车内项目不能在同一门店服务','result' => array('name' => $product->name));
//                                    return json_encode($response);
//                                }
                            }
                        }
                    }
                    if(empty($jiaoji)){
                        $response = Lang::get("error.service_shopping_car_not_in_shop_error_1031");
                        break;
                    }
                }else{
                    $data = json_encode($data);
                    $aas = AhpService::city_shop($data, $users);
                    $jiaoji = $aas['id'];
                }
            }
            //die;
            if(empty($jiaoji) && count($ji_first) != 1){
                $response = Lang::get("error.service_shopping_car_not_in_shop_error_1031");
                break;
            }
            if(!empty($jiaoji)){
                $shops = MaintenanceShops::where('status',1)->where('is_show',1)->whereIn('id',$jiaoji)->select('id','name','image','small_image','longitude','latitude','tel_phone')->get();
                if(!is_null($shops)){
                    foreach($shops as $v){
                        $order_count = Orders::getToMaintenanceShops(isset($users->id)?$users->id:Null,$v->id);
                        if($order_count != 0){
                            $v->to_shop = 1;
                        }else{
                            $v->to_shop = 0;
                        }
                    }
                    foreach($shops as $key=>$s){
                        $shops[$key]['shop_url']=Config::get('config.shop_img_url');
                    }
                }
            }
            $result = array('id' => $jiaoji, 'shops' => $shops);

            $response = array('code' => 0, 'msg' => 'ok','result' => $result);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "shopList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-09-03 14:03:32
     * @Description: 预约单下单(其他下单)
     * @link: http://www.activity.com/wechat/createOrder?token=c71e92cdf889b51f56921cc2830ce180&name=%E6%97%B6%E5%BA%86%E5%BA%86&phone=15910959937&short_name=%E4%BA%AC&car_no=A111111&book_time=2018-09-21&shop_id=1&book_hour=10:00:00-11:00:00&book_hour_id=51&city_id=1&order_source=1
     */
    public function qitacreateOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required',
                'phone' => 'required',
                'short_name' => 'required',
                'car_no' => 'required',
                'book_time' => 'required',
                'shop_id' => 'required',
                'book_hour' => 'required',
                'book_hour_id' => 'required',
                'city_id' => 'required',
                'order_source' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $args = Input::all();
            if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $args['short_name'])<=0){
                return json_encode(array('code' => 100332, 'msg' => '车牌号首字符不是中文'));break;
            }
//            if(!in_array('is_call',$args) || (in_array('is_call',$args) && !$args['is_call'])){
//                $args['is_call'] = 0;
//            }
            $args['user_id'] = $wechat_user->id;
            $order_id = Common::createOrderId();
            $city_change = ResourceCityType::getCity($args['city_id']);
            if(is_null($city_change)){
                $city_id = 1;
            }else{
                $city_id = $city_change->id;
            }
            //检测是否重复下单
            if(Orders::createOrderCheck3(Input::get('short_name').Input::get('car_no'),Input::get('shop_id'))){
                $response = Lang::get("error.order_ing_error_40003");
                break;
            }
            $ms = MaintenanceShops::where('id',Input::get('shop_id'))->where('status',1)->first();
            if(is_null($ms)){
                $response = Lang::get("error.order_shop_msg_error_40005");
                break;
            }
            $user_auth_car = UserAuthenticationCar::where('car_no',Input::get('short_name').Input::get('car_no'))->where('status',1)->first();
            if(Input::get('car_model_id')){
                $car_brand_id = Input::get('car_brand_id');
                $car_series_id = Input::get('car_series_id');
                $car_model_id = Input::get('car_model_id');
                $user_car_id = Input::get('user_car_id');
                $car_brand_name = Input::get('car_brand_name');
                $car_series_name = Input::get('car_series_name');
                $car_model_name = Input::get('car_model_name');
            }else{
                $car_brand_id = $car_series_id = $car_model_id = $user_car_id = 0;
                $car_brand_name = $car_series_name = $car_model_name = "";
            }
            if(!is_null($user_auth_car)){
                $car_brand_id = $user_auth_car->car_brand_id;
                $car_series_id = $user_auth_car->car_series_id;
                $car_model_id = $user_auth_car->car_model_id;
                $csi = DataCarStandardInfo::find($car_model_id);
                if($csi){
                    $car_brand_name = $csi->brand_name;
                    $car_series_name = $csi->series_name;
                    $car_model_name = $csi->model_name;
                }
                $uci = UserCarInfo::where('user_id',$wechat_user->id)->where('car_no',Input::get('short_name').Input::get('car_no'))->where('status',1)->first();
                if($uci){
                    $user_car_id = $uci->id;
                }
            }
            $status = Config::get('order.system_confirm_order_status');
            if($args['book_time'] == date('Y-m-d',time())){
                $status = Config::get('order.system_confirm_order_status');
            }
            $orders = new Orders();
            $orders->order_id = $order_id;
            $orders->user_id = $args['user_id'];
            $orders->city = $city_id;
            $orders->place = 2;
            $orders->book_time = $args['book_time'];
            $orders->book_hour = $args['book_hour'];
            $orders->shop_id =  isset($args['shop_id'])?$args['shop_id']:0;
            $orders->address =  "";
            $orders->name = $args['name'];
            $orders->tittle = "";
            $orders->phone = $args['phone'];
            $orders->pay_type = 1;
            $orders->user_car_id = $user_car_id;
            $orders->amount = 0;
            $orders->work_service = 0;
            $orders->status = $status;
            $orders->note = isset($args['remarks'])?$args['remarks']:"";
            $orders->created_at = Common::num2DateTime(time());
            $orders->car_brand_id = $car_brand_id;
            $orders->car_brand_name = $car_brand_name;
            $orders->car_series_id = $car_series_id;
            $orders->car_series_name = $car_series_name;
            $orders->car_model_id = $car_model_id;
            $orders->car_model_name = $car_model_name;
            $orders->car_no = $args['short_name'].$args['car_no'];
            $orders->outer_order_id = 0;
            $orders->engineer_id = 0;
            $orders->car_id = 0;
            $orders->mileage = 0;
            $orders->oil_meter = 0;
            $orders->order_source = $args['order_source'];//10-微站 2-app
            $orders->product_comment = "";
            $orders->discount_amount = 0;
            $orders->balance_amount = 0;
            //$orders->is_call = $args['is_call'];
            $orders->is_call = Input::get('is_call',1);
            $orders->save();

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order_id;
            $order_flows->status = $status;
            $order_flows->user_id = $args['user_id'];
            $order_flows->type = 'custom';
            $order_flows->created_at = Common::num2DateTime(time());
            $order_flows->save();

            $order_maintenance = new OrderMaintence();
            $order_maintenance->boot_date = $args['book_time'];
            $order_maintenance->order_id = $order_id;
            $order_maintenance->maintenance_type = 'shop';
            $order_maintenance->maintenance_id = isset($args['shop_id'])?$args['shop_id']:0; //如果type是car 上门车还没分配 不知道是谁 所以存0 如果是shop 即门店id
            $order_maintenance->time_prat_id = $args['book_hour_id'];
            $order_maintenance->save();

            $service_type_name = "";
            $service_types = Input::get('service_type');
            if($service_types){
                $arr_id = explode(',',rtrim($service_types,','));
                if(count($arr_id)){
                    foreach($arr_id as $_a){
                        $ot = new OrderType();
                        $ot->order_id = $order_id;
                        $ot->order_type = $_a;
                        $ot->save();
                        $service_type_name .= Orders::$service_type[$_a].'/';
                    }
                }
            }

            try {
                NewsLog::NewsPush($args['user_id'],$order_id,1,0,'订单已确认','您的订单已确认，请准时到达门店哦。');
            } catch (Exception $e) {
                Log::error("error", array("system" => "api3.0" ,"event" => "qitacreateOrder", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.run_exception");
//                break;
            }

            if(Config::get('u_meng_push.is_open_u_meng_push') ==1 && Input::get('is_app') ==1){
                Orders::notifyUserOrderStatus($args['user_id'],$order_id,'订单已确认','您的订单已确认，请准时到达门店哦。');
            }

            if(Input::get('is_app') != 1){ //1-代表app
                try {
                    if($orders->is_call == 1){
                        $is_call = '需要门店回电';
                    }else{
                        $is_call = '';
                    }
                    $shop = MaintenanceShops::where('id',$orders->shop_id)->first();
                    $templateId = Config::get('config.templateId');
                    $url = Config::get('config.redirect_url').'/order/show?is_wash=0&order_id='.$order_id;
                    $data = array(
                        "first"  => "亲爱的车主您好，您的预约已提交成功，欢迎您届时光临。",
                        "keyword1" =>  date("m",strtotime($orders->book_time)).'月'.date('d',strtotime($orders->book_time)).'日',
                        "keyword2"   => $orders->car_no."  ".trim($service_type_name.$is_call,'/'),
                        "keyword3"  => $shop->name,
                        "keyword4" => $shop->tel_phone,
                        "keyword5" => $shop->address,
                        "remark" => "到店后，请提供预约车牌号，点击查看详情"
                    );
                    WechatOauthController::sendMessage($wechat_user->openid,$templateId,$data,$url);
                } catch (Exception $e) {
                    Log::error("error", array("system" => "api3.0" ,"event" => "qitacreateOrder", 'input' =>Input::all() ,"exception" => $e));
                    //$response = Lang::get("error.order_create_msg_error_40004");
                    //break;
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_id));
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "qitacreateOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:          sqq
     * @DateTime:        2018-07-24 下午15:00
     * @Description:     api3.0 服务分类
     * @param string $token             用户token
     * @param int $model_id             车辆车型id
     * @link: http://www.activity.com/wechat/api3.0/service/serviceType
     */
    public function serviceType(){
        $validator = Validator::make(Input::all(),
            array(
                //'city_id' =>'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //根据服务分类
            $product_class = ProductClassification::get()->toArray();
            if($product_class){
                $service_list_recommend = Config::get('config.service_list_recommend_icon');
                array_unshift($product_class,$service_list_recommend);
            }
            array_push($product_class,Config::get('config.service_list_qita_icon'));

            if(!is_null($product_class)){
                foreach($product_class as $key => $val){
                    if($val['id'] != 100){
                        $product_class[$key]['icon'] = Config::get('config.service_list_icon_url').$val['icon'];
                        $product_class[$key]['click_icon'] = Config::get('config.service_list_icon_url').$val['click_icon'];
                    }
                }
            }

            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $product_class
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "serviceType", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:          sqq
     * @DateTime:        2018-07-24 下午15:00
     * @Description:     api3.0 服务    [ C端服务列表最新接口、S5 ]
     * @param string $token             用户token
     * @param int $model_id             车辆车型id
     * @link ： http://www.activity.com/wechat/api3.0/service/serviceListS5?city=%E5%8C%97%E4%BA%AC%E5%B8%82&classify=1&model=3&shop_id=1
     */
    public function serviceListS5(){
        $validator = Validator::make(Input::all(),
            array(
//                'token' => 'required',
//                'brand' => 'required',
//                'series' => 'required',
//                'year' => 'required',
                'city' => 'required',
                'classify' => 'required',
                //'model' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            if(Input::get("token")){
                $users = $this->verificationUserToken(Input::get("token"),$response);
                if(is_null($users)){
                    break;
                }
            }else{
                $users = (object)[];
                $users->id = 0;
            }

            //获取参数
            $brand = Input::get('brand');
            $series = Input::get('series');
            $year = urldecode(Input::get('year'));
            $model = Input::get('model');
            $city_name = Input::get('city');
            $shop_id = Input::get('shop_id');
            $classification = Input::get('classify');
            $type = Input::get('type');
            header("Content-type:text/html;charset=utf-8");
            //判断城市是否开放
            $city_id = PublicApi::Judge_city($city_name);
            if($city_id == 0){
                //城市未开放
                $response = Lang::get("error.service_list_city_empty_error_30011");
                break;
            }

            //判断当前城市是否有门店开放
            $shop = MaintenanceShops::where('status',1)->where('city_id',$city_id)->where('is_show',1)->first();
            if(empty($shop)){
                //城市没有适配门店
                $response = Lang::get("error.service_list_city_shop_empty_error_30012");
                break;
            }

            //判断分类是否存在
            $product_class = ProductClassification::select('id')->get();
            if(is_null($product_class)){
                $response = Lang::get("error.service_classification_empty_error_30014");
                break;
            }
            if(!is_null($product_class)){
                $product_class = $product_class->toArray();
                $product_id = array_column($product_class, 'id');
                if($classification != 0 && $classification != 100 && !in_array($classification, $product_id)){
                    $response = Lang::get("error.service_classification_empty_error_30014");
                    break;
                }
            }
            $service = [];

            if(!empty($model)){
                //查询ahp配置的当前分类的服务
                if($classification == 0){
                    $ahp_service = AhpService::where('status',1)->where('is_recommend',1)->select('id','service_name','classify','service_type','thumbnail','first_picture')->get();
                }elseif($classification == 100){
                    //其他服务直接返回
                    $ahp_service = Config::get('config.service_list_qita_icon')['ahp_service'];
                    $response = array('code' => 0, 'msg' => 'ok', 'result' => array('serviceList' => $ahp_service));
                    return json_encode($response);
                }else{
                    $ahp_service = AhpService::where('classify',$classification)->where('status',1)->select('id','service_name','classify','service_type','thumbnail','first_picture')->get();
                }

                //调用公众方法，判断服务是否符合条件
                $service = AhpService::serviceShowNew($ahp_service, $model, $city_id, $shop_id, $type);
                if($service){
                    foreach($service as $key => $val){
                        if(!(isset($val['service']) && $val['service'])){
                            unset($service[$key]);
                        }
                    }
                    $service = array_values($service);
                }
            }
            $response = [
                'is_login' => is_null($users) ? 1 : 2,  //1-未登录 2-已登录
                'serviceList' => $service,
                'APP_weizhan_service_url' => Config::get('config.APP_weizhan_service_url')
            ];


            $response = array('code' => 0, 'msg' => 'ok', 'result' => $response);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "wechat/api3.0/serviceList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:          sqq
     * @DateTime:        2018-09-18 下午17:10
     * @Description:     api3.0 服务 S5   [ C端服务详情 基础信息接口  配合serviceShowPrice接口使用]
     * @param string $token             用户token
     * @param int $id                 服务包id
     * @param int $city                 城市名称
     * @link：http://www.activity.com/wechat/api3.0/service/serviceShowS5?id=35&city=%E5%8C%97%E4%BA%AC%E5%B8%82&car_model_id=3
     */
    public function serviceShowS5(){
        $validator = Validator::make(Input::all(),
            array(
                //'token' => 'required',
                'id' => 'required',
                'city' => 'required',
                'car_model_id' => 'required',
                //'car_model_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //获取参数
            $id = Input::get('id');
            $city_name = Input::get('city');
            $car_model_id = Input::get('car_model_id');
            $shop_id = Input::get('shop_id');
            $type = Input::get('type');
            //判断城市是否开放
            $city_id = PublicApi::Judge_city($city_name);
            if($city_id == 0){
                //城市未开放
                $response = Lang::get("error.service_list_city_empty_error_30011");
                break;
            }

            //判断当前城市是否有门店开放
            $shop = MaintenanceShops::where('status',1)->where('city_id',$city_id)->where('is_show',1)->first();
            if(empty($shop)){
                //城市没有适配门店
                $response = Lang::get("error.service_list_city_shop_empty_error_30012");
                break;
            }

            //查询服务包基本信息
            $service = AhpService::with('desc')->where('id',$id)->where('status',1)->select('id','service_name','thumbnail','first_picture','service_type')->get();
            if(is_null($service)){
                $response = Lang::get("error.service_show_empty_error_30013");
                break;
            }

            $service = AhpService::serviceShowNew($service, $car_model_id, $city_id, $shop_id, $type);
            if(!is_null($service)){
                if(isset($service[0]['service'])){
                    foreach($service[0]['service'] as $_key => $_val){
                        if($_val){
                            $desc_id = AhpServiceMktCms::where('service_id',$id)->where('mkt_cms_id',$_val['id'])->first();
                            $detail = AhpServiceMktCms::join('ahp_service_mkt_cms_desc','ahp_service_mkt_cms.id','=','ahp_service_mkt_cms_desc.service_mkt_cms_id')->where('ahp_service_mkt_cms_desc.service_mkt_cms_id',$desc_id['id'])->select('ahp_service_mkt_cms_desc.desc')->get();
                            if(!is_null($detail)){
                                $service[0]['service'][$_key]['detail'] = array_column($detail->toArray(),'desc');
                            }
                        }
                    }
                    $service[0]['service'] = array_values($service[0]['service']);
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $service);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "serviceShow", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:          sqq
     * @DateTime:        2018-09-18 下午17:10
     * @Description:     api3.0 服务去预约效验是否有匹配门店
     * @param string $token             用户token
     * @link：http://www.activity.com/wechat/api3.0/service/serviceValidation?token=eac5606cd3f5d0405e9417a67bf6c5cf
     */
    public function serviceValidation(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //查询购物车是否有当前用户的商品
            $es = Shopping::where('status',1)->where('type',2)->where('user_id',$users->id)->get();
            if(is_null($es)){
                $response = Lang::get("error.user_car_choose_buy_error_1023");
                break;
            }
            $data = [];
            if(!is_null($es)){
                foreach($es as $e_k => $e_v){
                    $data[] =[
                        'id' => $e_v->mkt_cms_id,
                        'service_type' => $e_v->service_type,
                    ];
                }
                $aas = [];
                $jiaoji = [];
                $ji_first = [];
                if(sizeof($data) > 1){
                    foreach($data as $k => $v){
                        $a = array($v);
                        $data = json_encode($a);
                        $aas[] = AhpService::city_shop($data, $users);
                        foreach($aas as $_k => $_v){
                            if($k == 0){
                                $ji_first = $_v['id'];
                                $jiaoji = $ji_first;
                            }else{
                                $jiaoji = array_intersect($jiaoji, $_v['id']);
                                if(empty($jiaoji)){
                                    if($v['service_type'] == 1){
                                        $product = ProductActivity::where('id',$v['id'])->select('name')->first();
                                    }else{
                                        $product = ProductPackage::where('id',$v['id'])->select('name')->first();
                                    }
                                    //$response = Lang::get("error.service_shopping_car_not_in_shop_error_1031");
                                    $response = array('code' => 1031, 'msg' => '购物车内项目不能在同一门店服务','result' => array('name' => $product->name));
                                    return json_encode($response);
                                }
                            }
                        }
                    }
                    if(empty($jiaoji)){
                        $response = Lang::get("error.service_shopping_car_not_in_shop_error_1031");
                        break;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "serviceValidation", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

}